Skip to content

PDF Split — Zig source

Split a PDF by page, chunk size, or custom ranges — entirely in your browser. Nothing uploads.

This is the Zig implementation — the same logic the interactive tool runs, in a shareable, citable form.

// pdf-split — Zig port: page-range planner + naming for the split-by-plan
// tool. Zig (0.15+), standard library only. Port of src/lib/pdf-split.ts —
// same logic as this dir's typescript.ts and the live Go twin at
// cli/pdf-split/pdf-split.go. No idiomatic Zig PDF library exists, so like
// the Go twin only the pure planner (parsePageRanges) and naming pass
// (planNames) are ported; the byte-level split executor stays out of scope.
const std = @import("std");

pub const Error = error{ Invalid, Unsupported, OutOfMemory };

/// PdfToolError: a coded, user-facing error (TS: PdfToolError from
/// src/lib/pdf-errors.ts). `message` points into the caller's buffer the
/// parse/format helpers filled in. The planner only ever raises
/// .invalid — .encrypted is load-time only.
pub const Code = enum { invalid, unsupported };

pub const PdfToolError = struct {
    code: Code,
    message: []const u8,
};

/// SplitPdf is not implemented in v1 (see header): byte-level page extraction
/// has no stdlib engine, mirroring the Go twin's ErrUnsupported.
pub const unsupported_message =
    "pdf-split: byte-level page extraction is not implemented in v1";

fn formatError(buf: []u8, comptime fmt: []const u8, args: anytype) PdfToolError {
    const message = std.fmt.bufPrint(buf, fmt, args) catch blk: {
        break :blk buf;
    };
    return .{ .code = .invalid, .message = message };
}

/// The inclusive 1-based range [a..b] (the TS range() helper).
fn spanRange(allocator: std.mem.Allocator, a: usize, b: usize) Error![]const usize {
    const pages = try allocator.alloc(usize, b - a + 1);
    for (pages, 0..) |*p, i| p.* = a + i;
    return pages;
}

fn allDigits(s: []const u8) bool {
    if (s.len == 0) return false;
    for (s) |c| {
        if (c < '0' or c > '9') return false;
    }
    return true;
}

/// Parse one trimmed token: a single page, or an a-b span (1-based,
/// inclusive). On failure fills err_buf/err and returns error.Invalid.
fn parseToken(
    allocator: std.mem.Allocator,
    t: []const u8,
    page_count: usize,
    err_buf: []u8,
    err: *PdfToolError,
) Error![]const usize {
    if (allDigits(t)) {
        const page = std.fmt.parseInt(usize, t, 10) catch {
            err.* = formatError(err_buf, "\"{s}\" is not a page, a-b range, \"all\", or \"N/chunk\".", .{t});
            return Error.Invalid;
        };
        if (page < 1 or page > page_count) {
            err.* = formatError(err_buf, "Page {d} is out of range (1\u{2013}{d}).", .{ page, page_count });
            return Error.Invalid;
        }
        const group = try allocator.alloc(usize, 1);
        group[0] = page;
        return group;
    }
    if (std.mem.indexOfScalar(u8, t, '-')) |dash| {
        const a_str = t[0..dash];
        const b_str = t[dash + 1 ..];
        if (std.mem.indexOfScalar(u8, b_str, '-') == null and
            allDigits(a_str) and allDigits(b_str))
        {
            const a = std.fmt.parseInt(usize, a_str, 10) catch unreachable;
            const b = std.fmt.parseInt(usize, b_str, 10) catch unreachable;
            if (b < a) {
                err.* = formatError(err_buf, "Range {d}-{d} descends \u{2014} use a-b with a \u{2264} b.", .{ a, b });
                return Error.Invalid;
            }
            if (a < 1 or b > page_count) {
                err.* = formatError(err_buf, "Range {d}-{d} is out of range (1\u{2013}{d}).", .{ a, b, page_count });
                return Error.Invalid;
            }
            return spanRange(allocator, a, b);
        }
    }
    err.* = formatError(err_buf, "\"{s}\" is not a page, a-b range, \"all\", or \"N/chunk\".", .{t});
    return Error.Invalid;
}

/// Pure planner — no PDF parsing on this path. Grammar:
///
///     'all'       -> [[1],[2],..,[page_count]]
///     'N/chunk'   -> groups of N pages in order (last group may be short)
///     'a-b,c-d,e' -> [[a..b],[c..d],[e]] (1-based, inclusive)
///
/// On failure fills err (message written into err_buf) and returns
/// error.Invalid — the same error classes as the TS planner. The caller
/// frees the returned groups (an arena works well).
pub fn parsePageRanges(
    allocator: std.mem.Allocator,
    spec: []const u8,
    page_count: usize,
    err_buf: []u8,
    err: *PdfToolError,
) Error![]const []const usize {
    const trimmed = std.mem.trim(u8, spec, " \t\r\n\x0b\x0c");
    if (trimmed.len == 0) {
        err.* = .{ .code = .invalid, .message = "Enter a page range first." };
        return Error.Invalid;
    }

    if (std.mem.eql(u8, trimmed, "all")) {
        const groups = try allocator.alloc([]const usize, page_count);
        for (groups, 0..) |*g, i| {
            const group = try allocator.alloc(usize, 1);
            group[0] = i + 1;
            g.* = group;
        }
        return groups;
    }

    // 'N/chunk' — fixed-size groups in order (last may be short).
    const suffix = "/chunk";
    if (std.mem.endsWith(u8, trimmed, suffix) and trimmed.len > suffix.len) {
        const prefix = trimmed[0 .. trimmed.len - suffix.len];
        if (!allDigits(prefix)) {
            err.* = formatError(err_buf, "\"{s}\" is not a page, a-b range, \"all\", or \"N/chunk\".", .{trimmed});
            return Error.Invalid;
        }
        const size = std.fmt.parseInt(usize, prefix, 10) catch {
            err.* = formatError(err_buf, "\"{s}\" is not a page, a-b range, \"all\", or \"N/chunk\".", .{trimmed});
            return Error.Invalid;
        };
        if (size < 1 or size > page_count) {
            err.* = formatError(err_buf, "Chunk size must be between 1 and {d}.", .{page_count});
            return Error.Invalid;
        }
        var list: std.ArrayList([]const usize) = .empty;
        var start: usize = 1;
        while (start <= page_count) : (start += size) {
            const end = @min(start + size - 1, page_count);
            try list.append(allocator, try spanRange(allocator, start, end));
        }
        return try list.toOwnedSlice(allocator);
    }

    // Comma-separated tokens: pages and a-b spans.
    var list: std.ArrayList([]const usize) = .empty;
    var it = std.mem.splitScalar(u8, trimmed, ',');
    while (it.next()) |raw| {
        const t = std.mem.trim(u8, raw, " \t\r\n\x0b\x0c");
        const group = try parseToken(allocator, t, page_count, err_buf, err);
        try list.append(allocator, group);
    }
    return try list.toOwnedSlice(allocator);
}

/// Chunk-shaped = partition of 1..n into equal runs of >=2 pages (last may be
/// short). Size-1 "chunks" are indistinguishable from 'all' — those stay
/// page-N.
fn chunkShaped(groups: []const []const usize) bool {
    if (groups.len < 2) return false;
    const size = groups[0].len;
    if (size < 2) return false;
    var next: usize = 1;
    for (groups, 0..) |g, i| {
        if (g[0] != next) return false;
        next = g[g.len - 1] + 1;
        if (i + 1 < groups.len and g.len != size) return false;
        if (i + 1 == groups.len and g.len > size) return false;
    }
    return true;
}

/// Pure naming for a planned split — the single source of truth shared by the
/// TS splitPdf and the island's live preview. Single page -> 'page-N.pdf';
/// chunk-shaped plan -> 'chunk-K.pdf' (K 1-based); contiguous group ->
/// 'pages-A-B.pdf'; otherwise 'pages-A,B.pdf' (joined).
pub fn planNames(
    allocator: std.mem.Allocator,
    groups: []const []const usize,
) Error![]const []const u8 {
    const chunk = chunkShaped(groups);
    const names = try allocator.alloc([]const u8, groups.len);
    for (groups, 0..) |g, i| {
        names[i] = blk: {
            if (chunk) break :blk try std.fmt.allocPrint(allocator, "chunk-{d}.pdf", .{i + 1});
            if (g.len == 1) break :blk try std.fmt.allocPrint(allocator, "page-{d}.pdf", .{g[0]});
            if (g[g.len - 1] - g[0] + 1 == g.len) {
                break :blk try std.fmt.allocPrint(allocator, "pages-{d}-{d}.pdf", .{ g[0], g[g.len - 1] });
            }
            var joined: std.ArrayList(u8) = .empty;
            try joined.appendSlice(allocator, "pages-");
            for (g, 0..) |p, j| {
                if (j > 0) try joined.append(allocator, ',');
                var pbuf: [24]u8 = undefined;
                const pstr = std.fmt.bufPrint(&pbuf, "{d}", .{p}) catch unreachable;
                try joined.appendSlice(allocator, pstr);
            }
            try joined.appendSlice(allocator, ".pdf");
            break :blk try joined.toOwnedSlice(allocator);
        };
    }
    return names;
}

/// SplitPdf would extract each group into its own output PDF. v1 does not
/// implement byte-level page extraction — see header — so it always returns
/// error.Unsupported. Callers should use parsePageRanges + planNames to
/// preview a plan and wait for the executor to land.
pub fn splitPdf(pdf: []const u8, groups: []const []const usize) Error!void {
    _ = pdf;
    _ = groups;
    return Error.Unsupported;
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →