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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The constants and code tables of the Brotli format (RFC 7932).//!//! Nothing here belongs to one direction: every table describes the format//! itself, and a compressor needs each of them as much as the decompressor//! does, read the other way round — from a length to its code rather than from//! a code to its length.
const std = @import("std");
/// The smallest window a stream may declare, as log2 of its size.pub const min_window_bits = 10;/// The largest window a stream may declare, as log2 of its size. The/// "large window" extension of the reference implementation goes to 30, but/// it is not part of RFC 7932 and is not supported.pub const max_window_bits = 24;
/// The largest backward distance a stream with a `window_bits` window may/// use (RFC 7932 §9.1). The top 16 positions are given up so that the/// special distance codes can reach slightly past the last distance.pub fn maxBackwardDistance(window_bits: u5) u32 { return (@as(u32, 1) << window_bits) - 16;}
/// The literal alphabet: one symbol per byte value.pub const num_literal_symbols = 256;/// The insert-and-copy length alphabet (RFC 7932 §5).pub const num_command_symbols = 704;/// The block count alphabet (RFC 7932 §6).pub const num_block_count_symbols = 26;/// The most block types a category may have, and the most prefix trees a/// context map may refer to.pub const max_block_types = 256;/// The largest value RLEMAX may have in a context map (RFC 7932 §7.3).pub const max_context_map_rle = 16;
/// Literal context IDs per literal block type (RFC 7932 §7.1).pub const literal_contexts = 64;/// Distance context IDs per distance block type (RFC 7932 §7.2).pub const distance_contexts = 4;
/// The number of distance codes that refer to the ring of past distances.pub const num_distance_short_codes = 16;/// The largest NPOSTFIX a meta-block header can carry.pub const max_npostfix = 3;/// The largest NDIRECT a meta-block header can carry: 15 << 3.pub const max_ndirect = 120;/// The most extra bits a distance code may have.pub const max_distance_bits = 24;
/// The size of the distance alphabet for a meta-block with the given/// parameters (RFC 7932 §4).pub fn distanceAlphabetSize(npostfix: u2, ndirect: u8) u16 { return num_distance_short_codes + @as(u16, ndirect) + (@as(u16, 2 * max_distance_bits) << npostfix);}
/// The largest distance alphabet any meta-block can have.pub const max_distance_symbols = distanceAlphabetSize(max_npostfix, max_ndirect);
/// The four last distances at the start of a stream, oldest first (RFC 7932/// §4). They are not reset between meta-blocks.pub const initial_distances = [4]u32{ 16, 15, 11, 4 };
/// The largest MLEN a meta-block header can carry (RFC 7932 §9.2): six/// nibbles of length, so a meta-block holds at most 2^24 bytes.pub const max_meta_block_len = 1 << 24;
/// The meta-block length a block category with a single block type behaves/// as if it had been given: longer than any meta-block, so the block never/// ends.////// This must stay no smaller than `max_meta_block_len`. A single-type/// category reads no block-count code, so its `remaining` keeps this value/// for the whole meta-block; every symbol it decodes also consumes from the/// meta-block's own byte count, which runs out first (or, at most, at the/// same moment). So the count never reaches zero mid-meta-block and a block/// switch is never attempted in a category that has only one type — the/// invalid state behind CVE-2026-111497, where the reference C decoder would/// switch blocks with a single block type and write out of bounds. The/// `types >= 2` assertion in `Decompressor.switchBlock` is the runtime half/// of this guarantee.pub const unbounded_block_length = 1 << 24;
test "a single-type block outlasts any meta-block (CVE-2026-111497)" { // If this ever fails, a single-type category's count could reach zero // inside a meta-block and `Decompressor.switchBlock` would be entered // with one block type. try std.testing.expect(unbounded_block_length >= max_meta_block_len);}
/// The longest code any prefix code in the format may assign.pub const max_code_length = 15;/// The symbols of the code length alphabet (RFC 7932 §3.5), and the order in/// which a complex prefix code lists their code lengths.pub const num_code_length_symbols = 18;pub const code_length_order = [num_code_length_symbols]u8{ 1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15 };/// The code length alphabet's code lengths are themselves written with a/// fixed code (RFC 7932 §3.5). Indexed by the next four bits of the stream,/// this gives how many of them the code occupies and the length it stands/// for.pub const code_length_code_bits = [16]u3{ 2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2, 3, 2, 2, 2, 4 };pub const code_length_code_value = [16]u3{ 0, 4, 3, 2, 0, 4, 3, 1, 0, 4, 3, 2, 0, 4, 3, 5 };/// The code length symbol that repeats the previous non-zero length.pub const repeat_previous_code_length = 16;/// The code length symbol that repeats a zero length.pub const repeat_zero_code_length = 17;/// The length symbol 16 repeats when no non-zero length has been seen yet.pub const initial_repeated_code_length = 8;
/// A code that stands for a range of lengths: the first of them, and how/// many extra bits follow the code to pick one from the range.pub const LengthCode = struct { base: u32, extra_bits: u5,};
/// The insert length codes (RFC 7932 §5).pub const insert_length_codes = [24]LengthCode{ .{ .base = 0, .extra_bits = 0 }, .{ .base = 1, .extra_bits = 0 }, .{ .base = 2, .extra_bits = 0 }, .{ .base = 3, .extra_bits = 0 }, .{ .base = 4, .extra_bits = 0 }, .{ .base = 5, .extra_bits = 0 }, .{ .base = 6, .extra_bits = 1 }, .{ .base = 8, .extra_bits = 1 }, .{ .base = 10, .extra_bits = 2 }, .{ .base = 14, .extra_bits = 2 }, .{ .base = 18, .extra_bits = 3 }, .{ .base = 26, .extra_bits = 3 }, .{ .base = 34, .extra_bits = 4 }, .{ .base = 50, .extra_bits = 4 }, .{ .base = 66, .extra_bits = 5 }, .{ .base = 98, .extra_bits = 5 }, .{ .base = 130, .extra_bits = 6 }, .{ .base = 194, .extra_bits = 7 }, .{ .base = 322, .extra_bits = 8 }, .{ .base = 578, .extra_bits = 9 }, .{ .base = 1090, .extra_bits = 10 }, .{ .base = 2114, .extra_bits = 12 }, .{ .base = 6210, .extra_bits = 14 }, .{ .base = 22594, .extra_bits = 24 },};
/// The copy length codes (RFC 7932 §5).pub const copy_length_codes = [24]LengthCode{ .{ .base = 2, .extra_bits = 0 }, .{ .base = 3, .extra_bits = 0 }, .{ .base = 4, .extra_bits = 0 }, .{ .base = 5, .extra_bits = 0 }, .{ .base = 6, .extra_bits = 0 }, .{ .base = 7, .extra_bits = 0 }, .{ .base = 8, .extra_bits = 0 }, .{ .base = 9, .extra_bits = 0 }, .{ .base = 10, .extra_bits = 1 }, .{ .base = 12, .extra_bits = 1 }, .{ .base = 14, .extra_bits = 2 }, .{ .base = 18, .extra_bits = 2 }, .{ .base = 22, .extra_bits = 3 }, .{ .base = 30, .extra_bits = 3 }, .{ .base = 38, .extra_bits = 4 }, .{ .base = 54, .extra_bits = 4 }, .{ .base = 70, .extra_bits = 5 }, .{ .base = 102, .extra_bits = 5 }, .{ .base = 134, .extra_bits = 6 }, .{ .base = 198, .extra_bits = 7 }, .{ .base = 326, .extra_bits = 8 }, .{ .base = 582, .extra_bits = 9 }, .{ .base = 1094, .extra_bits = 10 }, .{ .base = 2118, .extra_bits = 24 },};
/// The block count codes (RFC 7932 §6).pub const block_length_codes = [num_block_count_symbols]LengthCode{ .{ .base = 1, .extra_bits = 2 }, .{ .base = 5, .extra_bits = 2 }, .{ .base = 9, .extra_bits = 2 }, .{ .base = 13, .extra_bits = 2 }, .{ .base = 17, .extra_bits = 3 }, .{ .base = 25, .extra_bits = 3 }, .{ .base = 33, .extra_bits = 3 }, .{ .base = 41, .extra_bits = 3 }, .{ .base = 49, .extra_bits = 4 }, .{ .base = 65, .extra_bits = 4 }, .{ .base = 81, .extra_bits = 4 }, .{ .base = 97, .extra_bits = 4 }, .{ .base = 113, .extra_bits = 5 }, .{ .base = 145, .extra_bits = 5 }, .{ .base = 177, .extra_bits = 5 }, .{ .base = 209, .extra_bits = 5 }, .{ .base = 241, .extra_bits = 6 }, .{ .base = 305, .extra_bits = 6 }, .{ .base = 369, .extra_bits = 7 }, .{ .base = 497, .extra_bits = 8 }, .{ .base = 753, .extra_bits = 9 }, .{ .base = 1265, .extra_bits = 10 }, .{ .base = 2289, .extra_bits = 11 }, .{ .base = 4337, .extra_bits = 12 }, .{ .base = 8433, .extra_bits = 13 }, .{ .base = 16625, .extra_bits = 24 },};
/// What an insert-and-copy length symbol stands for (RFC 7932 §5).pub const Command = struct { /// An index into `insert_length_codes`. insert_code: u5, /// An index into `copy_length_codes`. copy_code: u5, /// The command reuses the last distance, and no distance code follows /// it in the stream. implicit_distance: bool,};
/// The insert and copy length code ranges each block of 64 insert-and-copy/// symbols covers, in symbol order. The first two blocks also imply/// distance code 0.pub const command_cells = [11]struct { insert_base: u5, copy_base: u5 }{ .{ .insert_base = 0, .copy_base = 0 }, .{ .insert_base = 0, .copy_base = 8 }, .{ .insert_base = 0, .copy_base = 0 }, .{ .insert_base = 0, .copy_base = 8 }, .{ .insert_base = 8, .copy_base = 0 }, .{ .insert_base = 8, .copy_base = 8 }, .{ .insert_base = 0, .copy_base = 16 }, .{ .insert_base = 16, .copy_base = 0 }, .{ .insert_base = 8, .copy_base = 16 }, .{ .insert_base = 16, .copy_base = 8 }, .{ .insert_base = 16, .copy_base = 16 },};
/// Splits an insert-and-copy length symbol into its parts.pub fn command(symbol: u16) Command { std.debug.assert(symbol < num_command_symbols); const cell = command_cells[symbol >> 6]; return .{ .insert_code = cell.insert_base + @as(u5, @intCast((symbol >> 3) & 7)), .copy_code = cell.copy_base + @as(u5, @intCast(symbol & 7)), .implicit_distance = symbol < 128, };}
/// The insert length code for an insert of `length` bytes: the code whose/// range holds it.pub fn insertLengthCode(length: u32) u5 { return lengthCode(&insert_length_codes, length);}
/// The copy length code for a copy of `length` bytes, which must be at/// least 2.pub fn copyLengthCode(length: u32) u5 { std.debug.assert(length >= 2); return lengthCode(©_length_codes, length);}
/// The block count code for a block of `length` symbols, which must be at/// least 1.pub fn blockLengthCode(length: u32) u5 { std.debug.assert(length >= 1); return lengthCode(&block_length_codes, length);}
fn lengthCode(table: []const LengthCode, length: u32) u5 { var i: usize = table.len - 1; while (table[i].base > length) i -= 1; std.debug.assert(length - table[i].base < @as(u32, 1) << table[i].extra_bits); return @intCast(i);}
/// Which of the cells 2..10 holds each pair of insert and copy code ranges,/// indexed by `insert_code >> 3` and then `copy_code >> 3`.const explicit_cells = [3][3]u16{ .{ 2, 3, 6 }, .{ 4, 5, 8 }, .{ 7, 9, 10 } };
/// The insert-and-copy length symbol for an insert code and a copy code/// (RFC 7932 §5). With `implicit_distance`, the symbol says the command/// reuses the last distance, which only the first two cells can: it must/// have an insert code below 8 and a copy code below 16. The inverse of/// `command`.pub fn commandSymbol(insert_code: u5, copy_code: u5, implicit_distance: bool) u16 { const low = (@as(u16, insert_code & 7) << 3) | (copy_code & 7); if (implicit_distance) { std.debug.assert(insert_code < 8 and copy_code < 16); return (@as(u16, copy_code >> 3) << 6) | low; } return (explicit_cells[insert_code >> 3][copy_code >> 3] << 6) | low;}
/// A distance written as a distance code and the extra bits after it.pub const DistanceCode = struct { code: u16, extra_bits: u5, extra: u32,};
/// The distance code and extra bits that stand for `distance` in a/// meta-block with these parameters, without using the short codes for past/// distances (RFC 7932 §4).pub fn distanceCode(distance: u32, npostfix: u2, ndirect: u8) DistanceCode { std.debug.assert(distance > 0); if (distance <= ndirect) { return .{ .code = @intCast(num_distance_short_codes + distance - 1), .extra_bits = 0, .extra = 0 }; } // The inverse of the RFC's formula, which is easier to follow written in // terms of `dist`: the distance past the direct codes, offset so that // its top two bits pick the code and the rest are the extra bits. const dist: u32 = (distance - ndirect - 1) + (@as(u32, 1) << (@as(u5, npostfix) + 2)); const bucket: u5 = @intCast(std.math.log2_int(u32, dist) - 1); const postfix = dist & ((@as(u32, 1) << npostfix) - 1); const prefix = (dist >> bucket) & 1; const offset = (2 + prefix) << bucket; const nbits: u5 = bucket - npostfix; const code = num_distance_short_codes + @as(u32, ndirect) + (((2 * (@as(u32, nbits) - 1)) + prefix) << npostfix) + postfix; return .{ .code = @intCast(code), .extra_bits = nbits, .extra = (dist - offset) >> npostfix };}
/// The distance context ID for a copy of `copy_length` bytes (RFC 7932 §7.2).pub fn distanceContext(copy_length: u32) u2 { return if (copy_length > 4) 3 else @intCast(copy_length - 2);}
test "length code tables are contiguous" { // Each code's range starts where the previous one's ended, which is the // property the tables in the RFC are printed to show. for ([_][]const LengthCode{ &insert_length_codes, ©_length_codes, &block_length_codes }) |table| { for (table[0 .. table.len - 1], table[1..]) |a, b| { try std.testing.expectEqual(b.base, a.base + (@as(u32, 1) << a.extra_bits)); } } // The ranges the RFC prints for the last code of each table. try std.testing.expectEqual(16799809, insert_length_codes[23].base + (1 << 24) - 1); try std.testing.expectEqual(16779333, copy_length_codes[23].base + (1 << 24) - 1); try std.testing.expectEqual(16793840, block_length_codes[25].base + (1 << 24) - 1);}
test "command symbols match the cells of RFC 7932 §5" { try std.testing.expectEqual(Command{ .insert_code = 0, .copy_code = 0, .implicit_distance = true }, command(0)); try std.testing.expectEqual(Command{ .insert_code = 7, .copy_code = 15, .implicit_distance = true }, command(127)); try std.testing.expectEqual(Command{ .insert_code = 0, .copy_code = 0, .implicit_distance = false }, command(128)); try std.testing.expectEqual(Command{ .insert_code = 0, .copy_code = 16, .implicit_distance = false }, command(384)); try std.testing.expectEqual(Command{ .insert_code = 16, .copy_code = 0, .implicit_distance = false }, command(448)); try std.testing.expectEqual(Command{ .insert_code = 23, .copy_code = 23, .implicit_distance = false }, command(703));}
test "insert and copy length codes cover every length" { for (0..30000) |len| { const ic = insertLengthCode(@intCast(len)); const i = insert_length_codes[ic]; try std.testing.expect(len >= i.base and len - i.base < @as(u32, 1) << i.extra_bits); if (len < 2) continue; const cc = copyLengthCode(@intCast(len)); const c = copy_length_codes[cc]; try std.testing.expect(len >= c.base and len - c.base < @as(u32, 1) << c.extra_bits); } try std.testing.expectEqual(23, insertLengthCode(16799809)); try std.testing.expectEqual(23, copyLengthCode(16779333));}
test "commandSymbol is the inverse of command" { for (0..num_command_symbols) |sym| { const c = command(@intCast(sym)); try std.testing.expectEqual(sym, commandSymbol(c.insert_code, c.copy_code, c.implicit_distance)); }}
test "distanceCode is the inverse of the RFC's formula" { const distances = [_]u32{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 15, 16, 17, 100, 1000, 65535, 65536, (1 << 24) - 16 }; for (0..4) |npostfix| { for ([_]u8{ 0, 1, 15, 120 }) |ndirect_high| { const np: u2 = @intCast(npostfix); const ndirect: u8 = @min(ndirect_high, @as(u8, 15) << np); for (distances) |d| { const dc = distanceCode(d, np, ndirect); try std.testing.expect(dc.code < distanceAlphabetSize(np, ndirect)); // Decode it as RFC 7932 §4 does. const direct_end = num_distance_short_codes + @as(u32, ndirect); const back: u32 = if (dc.code < direct_end) dc.code - 15 else blk: { const x = dc.code - direct_end; const ndistbits: u5 = @intCast(1 + (x >> (@as(u5, np) + 1))); try std.testing.expectEqual(ndistbits, dc.extra_bits); const hcode = x >> np; const lcode = x & ((@as(u32, 1) << np) - 1); const offset = ((2 + (hcode & 1)) << ndistbits) - 4; break :blk ((offset + dc.extra) << np) + lcode + ndirect + 1; }; try std.testing.expectEqual(d, back); } } }}
test "distance alphabet sizes" { try std.testing.expectEqual(64, distanceAlphabetSize(0, 0)); try std.testing.expectEqual(520, max_distance_symbols);}