Something went wrong. Try again.
Brotli (RFC 7932) compression and decompression for Zig 0.17, with sans-I/O streaming cores and std.Io adapters.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The compressor, checked by decompressing what it makes. The inputs are//! what the test vectors decompress to.//!//! Interoperability with the reference implementation is checked outside//! the test binary, by `zig build interop`.
const std = @import("std");const brotli = @import("brotli");const drive = @import("drive.zig");const vectors = @import("vectors.zig").vectors;
/// The vectors' outputs, decompressed once and shared by every test here.fn inputs(gpa: std.mem.Allocator, max_len: usize) ![][]u8 { var list: std.ArrayList([]u8) = .empty; errdefer { for (list.items) |b| gpa.free(b); list.deinit(gpa); } for (vectors) |v| { if (v.length > max_len) continue; try list.append(gpa, try brotli.decompressAlloc(gpa, v.compressed, v.length)); } return list.toOwnedSlice(gpa);}
fn freeInputs(gpa: std.mem.Allocator, list: [][]u8) void { for (list) |b| gpa.free(b); gpa.free(list);}
fn roundTrip(gpa: std.mem.Allocator, data: []const u8, options: brotli.Compressor.Options) !void { const c = try brotli.compressAlloc(gpa, data, options); defer gpa.free(c); try std.testing.expect(c.len <= brotli.Compressor.maxCompressedSize(data.len)); const d = try brotli.decompressAlloc(gpa, c, data.len); defer gpa.free(d); try std.testing.expectEqualSlices(u8, data, d);}
test "every quality, every input" { const gpa = std.testing.allocator; const list = try inputs(gpa, 1 << 20); defer freeInputs(gpa, list); for (list) |data| { for (0..brotli.Compressor.max_quality + 1) |q| { errdefer std.debug.print("{d} bytes at quality {d}\n", .{ data.len, q }); try roundTrip(gpa, data, .{ .quality = @intCast(q) }); } }}
test "window sizes, including ones the input overruns many times" { const gpa = std.testing.allocator; const list = try inputs(gpa, 1 << 20); defer freeInputs(gpa, list); for (list) |data| { for ([_]u5{ 10, 11, 16, 17, 18, 24 }) |w| { for ([_]u4{ 0, 3, 6 }) |q| { errdefer std.debug.print("{d} bytes, window {d}, quality {d}\n", .{ data.len, w, q }); try roundTrip(gpa, data, .{ .quality = q, .window_bits = w }); } } }}
test "copies reaching across a wrapped 16 MiB window" { const gpa = std.testing.allocator; const v = for (vectors) |v| { if (std.mem.eql(u8, v.name, "far-copies-q5-w24")) break v; } else unreachable; const data = try brotli.decompressAlloc(gpa, v.compressed, v.length); defer gpa.free(data); const c = try brotli.compressAlloc(gpa, data, .{ .quality = 4, .window_bits = 24 }); defer gpa.free(c); // The copies are what make it small: the 64 KiB block of noise appears // three times and is stored once. try std.testing.expect(c.len < 80 << 10); const d = try brotli.decompressAlloc(gpa, c, data.len); defer gpa.free(d); try std.testing.expect(std.mem.eql(u8, data, d));}
/// Compresses `data` handing over `in_step` bytes of input and `out_step`/// bytes of room at a time, with a flush every `flush_every` bytes of input/// if that is not zero. After each flush, what has come out so far must/// decompress to all of the input so far.fn compressInPieces(gpa: std.mem.Allocator, data: []const u8, options: brotli.Compressor.Options, in_step: usize, out_step: usize, flush_every: usize) ![]u8 { var c: brotli.Compressor = .init(gpa, options); defer c.deinit(); var out: std.ArrayList(u8) = .empty; defer out.deinit(gpa); var d: brotli.Decompressor = .init(gpa, .{}); defer d.deinit(); var check: std.ArrayList(u8) = .empty; defer check.deinit(gpa); var checked: usize = 0;
var pos: usize = 0; var next_flush = if (flush_every == 0) data.len else flush_every; while (true) { const end = @min(data.len, pos + in_step, next_flush); const op: brotli.Compressor.Operation = if (end == data.len) .finish else if (end == next_flush) .flush else .process; try out.ensureUnusedCapacity(gpa, out_step); const r = try c.compress(data[pos..end], out.unusedCapacitySlice()[0..out_step], op); pos += r.read; out.items.len += r.written; switch (r.status) { .need_output => continue, .done => break, .need_input => if (op == .flush) { // Everything so far must decompress now. while (true) { try check.ensureUnusedCapacity(gpa, 4096); const dr = try d.decompress(out.items[checked..], check.unusedCapacitySlice()); checked += dr.read; check.items.len += dr.written; if (dr.status == .need_input) break; } try std.testing.expectEqualSlices(u8, data[0..pos], check.items); next_flush = @min(data.len, pos + flush_every); }, } } return out.toOwnedSlice(gpa);}
test "in pieces, with and without flushes" { const gpa = std.testing.allocator; const list = try inputs(gpa, 300 << 10); defer freeInputs(gpa, list); const cases = [_][3]usize{ .{ 1, 1, 0 }, .{ 7, 3, 0 }, .{ 65537, 255, 0 }, .{ 4093, 4096, 10000 }, .{ 100, 1, 1 }, .{ 1 << 20, 1 << 20, 65536 }, }; for (list) |data| { for (cases) |cs| { // A flush after every byte of 80 KiB is a long wait for nothing // the other cases do not cover. if (cs[2] == 1 and data.len > 4096) continue; for ([_]u4{ 1, 5 }) |q| { errdefer std.debug.print("{d} bytes, steps {d}/{d}, flush every {d}, quality {d}\n", .{ data.len, cs[0], cs[1], cs[2], q }); const c = try compressInPieces(gpa, data, .{ .quality = q }, cs[0], cs[1], cs[2]); defer gpa.free(c); const d = try drive.decompress(gpa, c, c.len, data.len + 1, .reject); defer gpa.free(d); try std.testing.expectEqualSlices(u8, data, d); // Without flushes, the pieces make no difference to the // stream. if (cs[2] == 0) { const whole = try brotli.compressAlloc(gpa, data, .{ .quality = q }); defer gpa.free(whole); try std.testing.expectEqualSlices(u8, whole, c); } } } }}
test "incompressible input grows by no more than maxCompressedSize allows" { const gpa = std.testing.allocator; var prng: std.Random.DefaultPrng = .init(7); for ([_]usize{ 0, 1, 100, 65535, 65536, 65537, 300_000 }) |n| { const data = try gpa.alloc(u8, n); defer gpa.free(data); prng.random().bytes(data); for ([_]u4{ 0, 6, 11 }) |q| { const out = try gpa.alloc(u8, brotli.Compressor.maxCompressedSize(n)); defer gpa.free(out); const written = try brotli.compress(gpa, data, out, .{ .quality = q }); const d = try brotli.decompressAlloc(gpa, out[0..written], n); defer gpa.free(d); try std.testing.expectEqualSlices(u8, data, d); } } var small: [4]u8 = undefined; try std.testing.expectError(error.NoSpaceLeft, brotli.compress(gpa, "hello, hello, hello", &small, .{}));}
test "flush and finish" { const gpa = std.testing.allocator; var c: brotli.Compressor = .init(gpa, .{}); defer c.deinit(); var out: [64]u8 = undefined;
// A flush with nothing to flush writes what it must and nothing more. var r = try c.compress("", &out, .flush); try std.testing.expectEqual(brotli.Status.need_input, r.status); const first = r.written; r = try c.compress("", out[first..], .flush); try std.testing.expectEqual(0, r.written);
r = try c.compress("abc", out[first..], .finish); try std.testing.expectEqual(brotli.Status.done, r.status); try std.testing.expect(c.isDone()); const total = first + r.written; const d = try brotli.decompressAlloc(gpa, out[0..total], 10); defer gpa.free(d); try std.testing.expectEqualStrings("abc", d);
// Finished is finished. r = try c.compress("", &out, .finish); try std.testing.expectEqual(brotli.Status.done, r.status); try std.testing.expectEqual(0, r.written); try std.testing.expectError(error.StreamFinished, c.compress("more", &out, .process));
// And reset starts again, making exactly what a new compressor would. c.reset(); r = try c.compress("abc", &out, .finish); const again = try brotli.compressAlloc(gpa, "abc", .{}); defer gpa.free(again); try std.testing.expectEqualSlices(u8, again, out[0..r.written]);}
test "the empty stream" { const gpa = std.testing.allocator; for ([_]u5{ 10, 15, 16, 17, 18, 22, 24 }) |w| { const c = try brotli.compressAlloc(gpa, "", .{ .window_bits = w }); defer gpa.free(c); // WBITS takes one, four or seven bits, then two for the end. try std.testing.expectEqual(@as(usize, if (w == 16 or w >= 18) 1 else 2), c.len); const d = try brotli.decompressAlloc(gpa, c, 0); defer gpa.free(d); try std.testing.expectEqual(0, d.len); }}
test "one compressor, many streams, the same as fresh ones" { const gpa = std.testing.allocator; const list = try inputs(gpa, 300 << 10); defer freeInputs(gpa, list); var c: brotli.Compressor = .init(gpa, .{ .quality = 7 }); defer c.deinit(); for (list) |data| { c.reset(); const out = try gpa.alloc(u8, brotli.Compressor.maxCompressedSize(data.len)); defer gpa.free(out); const r = try c.compress(data, out, .finish); try std.testing.expectEqual(brotli.Status.done, r.status); const fresh = try brotli.compressAlloc(gpa, data, .{ .quality = 7 }); defer gpa.free(fresh); try std.testing.expectEqualSlices(u8, fresh, out[0..r.written]); }}
test "the static dictionary and context modeling earn their keep" { const gpa = std.testing.allocator; // Short English, too short to repeat itself: only the dictionary can // help. const text = "The quick brown fox jumps over the lazy dog. Information about the " ++ "International Business of the United States, with the following details, " ++ "available from the department of commerce and the national government."; const plain = try brotli.compressAlloc(gpa, text, .{ .quality = 3 }); defer gpa.free(plain); const with_dictionary = try brotli.compressAlloc(gpa, text, .{ .quality = 5 }); defer gpa.free(with_dictionary); try std.testing.expect(with_dictionary.len * 10 < plain.len * 8);
// Signed samples, where the context of a byte is the bytes before it. const v = for (vectors) |v| { if (std.mem.eql(u8, v.name, "samples-q11")) break v; } else unreachable; const samples = try brotli.decompressAlloc(gpa, v.compressed, v.length); defer gpa.free(samples); const flat = try brotli.compressAlloc(gpa, samples, .{ .quality = 3 }); defer gpa.free(flat); const modeled = try brotli.compressAlloc(gpa, samples, .{ .quality = 5 }); defer gpa.free(modeled); try std.testing.expect(modeled.len * 100 < flat.len * 95); for ([_][]const u8{ with_dictionary, modeled }, [_][]const u8{ text, samples }) |c, want| { const d = try brotli.decompressAlloc(gpa, c, want.len); defer gpa.free(d); try std.testing.expectEqualSlices(u8, want, d); }}
test "block splitting and optimal parsing earn their keep" { const gpa = std.testing.allocator; const Case = struct { vector: []const u8, from: u4, to: u4, percent: usize }; // Text, noise and samples one after another: different statistics in // different stretches, which is what block splitting is for. And text, // where optimal parsing finds a better parse than the lazy one. const cases = [_]Case{ .{ .vector = "mixed-q11", .from = 6, .to = 7, .percent = 98 }, .{ .vector = "text-q11", .from = 9, .to = 11, .percent = 97 }, }; for (cases) |cs| { const v = for (vectors) |v| { if (std.mem.eql(u8, v.name, cs.vector)) break v; } else unreachable; const data = try brotli.decompressAlloc(gpa, v.compressed, v.length); defer gpa.free(data); const before = try brotli.compressAlloc(gpa, data, .{ .quality = cs.from }); defer gpa.free(before); const after = try brotli.compressAlloc(gpa, data, .{ .quality = cs.to }); defer gpa.free(after); errdefer std.debug.print("{s}: quality {d} {d} bytes, quality {d} {d} bytes\n", .{ cs.vector, cs.from, before.len, cs.to, after.len }); try std.testing.expect(after.len * 100 < before.len * cs.percent); const back = try brotli.decompressAlloc(gpa, after, data.len); defer gpa.free(back); try std.testing.expectEqualSlices(u8, data, back); }}
test "single-block-type streams decode across meta-block boundaries (CVE-2026-111497)" { // A category with one block type reads no block-count code; its count is // set to outlast any meta-block, so a block switch must never be // attempted for it. The reference C decoder would switch blocks with a // single block type and write out of bounds (CVE-2026-111497); the // `types >= 2` assertion in `Decompressor.switchBlock` fires here in a // safe build if that invariant is ever broken. Quality 0 does no block // splitting, so every category it emits has a single type; a payload past // one meta-block (2^24 bytes) makes the decoder cross meta-block // boundaries while those single-type counts are live. const gpa = std.testing.allocator; const n = (1 << 24) + (1 << 20); // just over one maximum meta-block const data = try gpa.alloc(u8, n); defer gpa.free(data); // Incompressible bytes force a literal-heavy stream; a repeated run would // compress to copies and drive the literal count far less. var prng: std.Random.DefaultPrng = .init(111497); prng.random().bytes(data); const c = try brotli.compressAlloc(gpa, data, .{ .quality = 0 }); defer gpa.free(c); const d = try brotli.decompressAlloc(gpa, c, data.len); defer gpa.free(d); try std.testing.expectEqualSlices(u8, data, d);}