// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Brotli (RFC 7932) for Zig, with no I/O. //! //! `Compressor` and `Decompressor` are the streaming cores: the caller hands //! either one bytes and room for output, in pieces as small or as large as it //! likes, and moves the bytes itself. Everything else is built on them: //! //! * `CompressReader` and `DecompressReader`, `std.Io.Reader`s over another //! reader; //! * `CompressWriter` and `DecompressWriter`, `std.Io.Writer`s that pass //! what comes out on to another writer; //! * `compressStream` and `decompressStream`, from a reader to a writer; //! * `compress`, `compressAlloc`, `decompress` and `decompressAlloc`, for //! data that is already in memory. //! //! The parts of the format that do not depend on direction — the code //! tables, the context model, the static dictionary and its transforms, //! canonical prefix codes, and the status a streaming call reports — are //! their own modules, used by both sides and exported below. const std = @import("std"); const Allocator = std.mem.Allocator; pub const Decompressor = @import("Decompressor.zig"); pub const DecompressReader = @import("DecompressReader.zig"); pub const DecompressWriter = @import("DecompressWriter.zig"); pub const Compressor = @import("Compressor.zig"); pub const CompressReader = @import("CompressReader.zig"); pub const CompressWriter = @import("CompressWriter.zig"); pub const Status = stream.Status; pub const Result = stream.Result; /// The streaming status and result types shared by the decompressor and, in /// time, a compressor. pub const stream = @import("stream.zig"); /// The constants and code tables of the format. pub const format = @import("format.zig"); /// Literal context modes and their lookup tables. pub const context = @import("context.zig"); /// The static dictionary. pub const dictionary = @import("dictionary.zig"); /// The static dictionary's word transforms. pub const transform = @import("transform.zig"); /// Canonical prefix codes and the decompressor's lookup tables for them. pub const prefix_code = @import("prefix_code.zig"); pub const DecompressError = Decompressor.Error || error{ /// The input ends before the stream does. Truncated, /// The input continues after the stream has ended. TrailingData, }; /// Decompresses the whole of `input`, which must be exactly one Brotli /// stream, into `output`, returning how many bytes were written. Fails with /// `error.NoSpaceLeft` if `output` is too small. pub fn decompress(gpa: Allocator, input: []const u8, output: []u8) (DecompressError || error{NoSpaceLeft})!usize { var d: Decompressor = .init(gpa, .{}); defer d.deinit(); const r = try d.decompress(input, output); return switch (r.status) { .done => if (r.read != input.len) error.TrailingData else r.written, .need_input => error.Truncated, .need_output => error.NoSpaceLeft, }; } /// Decompresses the whole of `input`, which must be exactly one Brotli /// stream, into memory allocated with `gpa`, which the caller owns. Fails /// with `error.StreamTooLong` rather than produce more than `limit` bytes. pub fn decompressAlloc(gpa: Allocator, input: []const u8, limit: usize) (DecompressError || error{StreamTooLong})![]u8 { var d: Decompressor = .init(gpa, .{}); defer d.deinit(); var out: std.ArrayList(u8) = .empty; defer out.deinit(gpa); var in = input; while (true) { if (out.items.len == out.capacity and out.items.len < limit) { try out.ensureUnusedCapacity(gpa, @min(limit - out.items.len, @max(out.items.len, 4096))); } const free = out.unusedCapacitySlice(); const r = try d.decompress(in, free[0..@min(free.len, limit - out.items.len)]); in = in[r.read..]; out.items.len += r.written; switch (r.status) { .done => { if (in.len != 0) return error.TrailingData; return out.toOwnedSlice(gpa); }, .need_input => return error.Truncated, .need_output => if (out.items.len >= limit) return error.StreamTooLong, } } } /// Compresses all of `input` into one Brotli stream in `output`, returning /// how many bytes were written. Fails with `error.NoSpaceLeft` if `output` /// is too small; `Compressor.maxCompressedSize` is always enough. pub fn compress(gpa: Allocator, input: []const u8, output: []u8, options: Compressor.Options) (Compressor.Error || error{NoSpaceLeft})!usize { var c: Compressor = .init(gpa, options); defer c.deinit(); const r = try c.compress(input, output, .finish); return if (r.status == .done) r.written else error.NoSpaceLeft; } /// Compresses all of `input` into one Brotli stream in memory allocated with /// `gpa`, which the caller owns. pub fn compressAlloc(gpa: Allocator, input: []const u8, options: Compressor.Options) Compressor.Error![]u8 { const out = try gpa.alloc(u8, Compressor.maxCompressedSize(input.len)); errdefer gpa.free(out); const n = compress(gpa, input, out, options) catch |e| switch (e) { error.NoSpaceLeft => unreachable, else => |ce| return ce, }; return gpa.realloc(out, n); } pub const DecompressStreamError = DecompressReader.Error || error{ /// Reading the input failed; the input reader has the details. ReadFailed, /// Writing the output failed; the output writer has the details. WriteFailed, }; /// Decompresses one Brotli stream from `input` to `output`, returning how /// many bytes it wrote. Anything in `input` after the end of the stream is /// left unread. `input` must have a buffer, as `DecompressReader.init` /// describes; `output` is not flushed. pub fn decompressStream(gpa: Allocator, input: *std.Io.Reader, output: *std.Io.Writer, options: Decompressor.Options) DecompressStreamError!usize { var d: DecompressReader = .init(gpa, input, &.{}, options); defer d.deinit(); return d.reader.streamRemaining(output) catch |e| switch (e) { error.ReadFailed => d.err orelse error.ReadFailed, error.WriteFailed => error.WriteFailed, }; } pub const CompressStreamError = Compressor.Error || error{ /// Reading the input failed; the input reader has the details. ReadFailed, /// Writing the output failed; the output writer has the details. WriteFailed, }; /// Compresses everything `input` has, to its end, into one Brotli stream /// written to `output`, returning how many bytes it wrote. `input` must /// have a buffer, as `CompressReader.init` describes; `output` is not /// flushed. pub fn compressStream(gpa: Allocator, input: *std.Io.Reader, output: *std.Io.Writer, options: Compressor.Options) CompressStreamError!usize { var c: CompressReader = .init(gpa, input, &.{}, options); defer c.deinit(); return c.reader.streamRemaining(output) catch |e| switch (e) { error.ReadFailed => c.err orelse error.ReadFailed, error.WriteFailed => error.WriteFailed, }; } test { std.testing.refAllDecls(@This()); _ = @import("BitReader.zig"); _ = @import("BitWriter.zig"); _ = @import("DictionaryIndex.zig"); _ = @import("block_split.zig"); _ = @import("histogram.zig"); _ = @import("literal_contexts.zig"); _ = @import("store.zig"); } test "decompressAlloc stops at its limit" { const gpa = std.testing.allocator; const input = [_]u8{ 0x40, 0x00, 0x10 } ++ "hello".* ++ [_]u8{0b11}; try std.testing.expectError(error.StreamTooLong, decompressAlloc(gpa, &input, 4)); const out = try decompressAlloc(gpa, &input, 5); defer gpa.free(out); try std.testing.expectEqualStrings("hello", out); const empty = try decompressAlloc(gpa, &.{0x06}, 0); defer gpa.free(empty); try std.testing.expectEqual(0, empty.len); } test "the empty stream" { // WBITS 16, ISLAST, ISLASTEMPTY: the shortest valid stream. var out: [1]u8 = undefined; try std.testing.expectEqual(0, try decompress(std.testing.allocator, &.{0x06}, &out)); } test "an uncompressed meta-block" { // WBITS 16; a meta-block that is not last, MNIBBLES 4, MLEN 5, // ISUNCOMPRESSED; padding; "hello"; then ISLAST, ISLASTEMPTY. // // bit 0 0 WBITS 16 // bit 1 0 ISLAST // bits 2-3 00 MNIBBLES 4 // bits 4-19 MLEN - 1 = 4 // bit 20 1 ISUNCOMPRESSED // bits 21-23 padding const input = [_]u8{ 0x40, 0x00, 0x10 } ++ "hello".* ++ [_]u8{0b11}; const out = try decompressAlloc(std.testing.allocator, &input, 100); defer std.testing.allocator.free(out); try std.testing.expectEqualStrings("hello", out); } test "compress round trip" { const gpa = std.testing.allocator; var repeated: [8000]u8 = undefined; for (&repeated, 0..) |*b, i| b.* = "abcdefgh"[i % 8]; const inputs = [_][]const u8{ "", "a", "hello hello hello hello world", &repeated }; for (inputs) |input| { for (0..Compressor.max_quality + 1) |q| { const c = try compressAlloc(gpa, input, .{ .quality = @intCast(q) }); defer gpa.free(c); const d = try decompressAlloc(gpa, c, input.len); defer gpa.free(d); try std.testing.expectEqualStrings(input, d); } } }