// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Canonical prefix codes (RFC 7932 §3.2). //! //! A prefix code travels as a list of code lengths, one per symbol, from which //! both ends derive the same codes. `assignCodes` is that derivation; //! `lengthsFromCounts` is how the compressor chooses the lengths in the first //! place, and `build` how the decompressor turns them into the lookup table //! it reads symbols with. //! //! The table has two levels. The first is indexed by the next `root_bits` //! bits of the stream and settles every code that short; a longer code's //! first-level entry links to a second-level table indexed by the bits after //! those. Brotli packs codes starting from their most significant bit while //! reading the stream from the least significant end, so tables are indexed //! by codes with their bits reversed. const std = @import("std"); const Allocator = std.mem.Allocator; const format = @import("format.zig"); pub const max_length = format.max_code_length; pub const root_bits = 8; const root_size = 1 << root_bits; /// One slot of a decoding table. pub const Entry = struct { /// For a leaf, the symbol. For a link, where the second-level table /// starts, counted in entries from the start of this code's table. value: u16, /// For a leaf, how many bits its code occupies at this level. For a link, /// how many bits index the second-level table. bits: u8, link: bool, }; pub const Error = error{InvalidPrefixCode}; /// Assigns the canonical code to each symbol with a non-zero length: codes of /// the same length are consecutive in symbol order, and shorter codes come /// lexicographically first. `codes[i]` is meaningful only where /// `lengths[i] != 0`. The lengths must describe a prefix code (as `build` /// checks), or the codes will not be one. pub fn assignCodes(lengths: []const u8, codes: []u16) void { std.debug.assert(codes.len >= lengths.len); var count: [max_length + 1]u16 = @splat(0); for (lengths) |l| count[l] += 1; count[0] = 0; var next: [max_length + 1]u16 = @splat(0); var code: u16 = 0; for (1..max_length + 1) |len| { code = (code + count[len - 1]) << 1; next[len] = code; } for (lengths, 0..) |l, sym| { if (l == 0) continue; codes[sym] = next[l]; next[l] += 1; } } /// Appends the decoding table for the code with these lengths to `table`. /// The code's table starts at the length `table` had on entry. /// /// The lengths must describe a complete prefix code, one whose codes leave no /// bit pattern unassigned — every code Brotli can transmit is one — with one /// exception: a code with a single non-zero length is a code of one symbol /// that occupies no bits at all, whatever the length says. pub fn build(gpa: Allocator, table: *std.ArrayList(Entry), lengths: []const u8) (Error || Allocator.Error)!void { var count: [max_length + 1]u16 = @splat(0); for (lengths) |l| { if (l > max_length) return error.InvalidPrefixCode; count[l] += 1; } count[0] = 0; const base = table.items.len; var used: usize = 0; for (count) |c| used += c; if (used == 0) return error.InvalidPrefixCode; if (used == 1) { const sym = for (lengths, 0..) |l, i| { if (l != 0) break i; } else unreachable; try table.appendNTimes(gpa, .{ .value = @intCast(sym), .bits = 0, .link = false }, root_size); return; } // Exactly complete: every bit pattern decodes to something, so the // decompressor never meets an empty slot. var left: i32 = 1; for (1..max_length + 1) |len| { left = (left << 1) - count[len]; if (left < 0) return error.InvalidPrefixCode; } if (left != 0) return error.InvalidPrefixCode; // Symbols sorted by code length, then by value: canonical code order. var offset: [max_length + 2]u16 = @splat(0); for (1..max_length + 1) |len| offset[len + 1] = offset[len] + count[len]; var sorted: [format.num_command_symbols]u16 = undefined; std.debug.assert(lengths.len <= sorted.len); for (lengths, 0..) |l, sym| { if (l == 0) continue; sorted[offset[l]] = @intCast(sym); offset[l] += 1; } // How long the longest code under each first-level prefix is, which // decides how big that prefix's second-level table must be. Codes come // in order of length, so the last one seen under a prefix is the // longest. var longest: [root_size]u8 = @splat(0); { var code: u32 = 0; var len: u8 = 1; for (sorted[0..used]) |sym| { const l = lengths[sym]; code <<= @intCast(l - len); len = l; if (l > root_bits) longest[code >> @intCast(l - root_bits)] = l; code += 1; } } try table.appendNTimes(gpa, undefined, root_size); var code: u32 = 0; var len: u8 = 1; for (sorted[0..used]) |sym| { const l = lengths[sym]; code <<= @intCast(l - len); len = l; defer code += 1; if (l <= root_bits) { const step = @as(usize, 1) << @intCast(l); var i: usize = reverse(code, l); while (i < root_size) : (i += step) { table.items[base + i] = .{ .value = sym, .bits = l, .link = false }; } continue; } const prefix = code >> @intCast(l - root_bits); const slot = base + reverse(prefix, root_bits); const sub_bits = longest[prefix] - root_bits; if (code & ((@as(u32, 1) << @intCast(l - root_bits)) - 1) == 0) { // The first code under this prefix: canonical order puts the // all-zero suffix first. const start = table.items.len - base; try table.appendNTimes(gpa, undefined, @as(usize, 1) << @intCast(sub_bits)); table.items[slot] = .{ .value = @intCast(start), .bits = sub_bits, .link = true }; } const sub = base + table.items[slot].value; const rest: u8 = l - root_bits; const step = @as(usize, 1) << @intCast(rest); var i: usize = reverse(code & ((@as(u32, 1) << @intCast(rest)) - 1), rest); while (i < @as(usize, 1) << @intCast(sub_bits)) : (i += step) { table.items[sub + i] = .{ .value = sym, .bits = rest, .link = false }; } } } /// Chooses code lengths for an alphabet whose symbols occur `counts` times, /// none longer than `limit`, writing them to `lengths` and returning how many /// symbols occur at all. With fewer than two, every length is zero: a code /// of one symbol, or of none, needs no bits. /// /// The lengths are those of a Huffman code, which is always complete. When /// the tree comes out deeper than `limit`, the rarest symbols are treated as /// more common than they are, doubling the floor under every count until it /// fits, as the reference implementation does. pub fn lengthsFromCounts(counts: []const u32, limit: u4, lengths: []u8) usize { std.debug.assert(counts.len <= format.num_command_symbols and lengths.len >= counts.len); std.debug.assert(limit >= 1); @memset(lengths[0..counts.len], 0); var symbols: [format.num_command_symbols]u16 = undefined; var n: usize = 0; for (counts, 0..) |c, sym| { if (c == 0) continue; symbols[n] = @intCast(sym); n += 1; } if (n < 2) return n; std.debug.assert(n <= @as(usize, 1) << limit); var floor: u64 = 1; while (!huffman(counts, symbols[0..n], floor, limit, lengths)) floor *= 2; return n; } /// Builds a Huffman tree over `symbols` with each count raised to at least /// `floor`, and writes the depth of each symbol to `lengths` unless the tree /// is deeper than `limit`, which it reports by returning false. fn huffman(counts: []const u32, symbols: []u16, floor: u64, limit: u4, lengths: []u8) bool { const n = symbols.len; const Ctx = struct { counts: []const u32, floor: u64, fn weight(ctx: @This(), sym: u16) u64 { return @max(ctx.counts[sym], ctx.floor); } fn lessThan(ctx: @This(), a: u16, b: u16) bool { const wa = ctx.weight(a); const wb = ctx.weight(b); return wa < wb or (wa == wb and a < b); } }; const ctx: Ctx = .{ .counts = counts, .floor = floor }; std.mem.sortUnstable(u16, symbols, ctx, Ctx.lessThan); // Leaves are nodes 0..n in order of weight, and the internal nodes // follow in the order they are made, which is also in order of weight; // so the two lightest nodes are always at the front of one queue or the // other. var weight: [2 * format.num_command_symbols]u64 = undefined; var parent: [2 * format.num_command_symbols]u16 = undefined; for (symbols, 0..) |sym, i| weight[i] = ctx.weight(sym); var leaf: usize = 0; var inner: usize = n; var next: usize = n; while (next < 2 * n - 1) : (next += 1) { var pair: [2]usize = undefined; for (&pair) |*p| { // Leaves first on a tie, which keeps the tree shallower. if (leaf < n and (inner == next or weight[leaf] <= weight[inner])) { p.* = leaf; leaf += 1; } else { p.* = inner; inner += 1; } } weight[next] = weight[pair[0]] + weight[pair[1]]; parent[pair[0]] = @intCast(next); parent[pair[1]] = @intCast(next); } // Depths from the root down: every node's parent was made after it. var depth: [2 * format.num_command_symbols]u8 = undefined; const root = 2 * n - 2; depth[root] = 0; var i = root; while (i > 0) { i -= 1; depth[i] = depth[parent[i]] + 1; if (i < n and depth[i] > limit) return false; } for (symbols, 0..) |sym, j| lengths[sym] = depth[j]; return true; } /// A symbol and how many bits of the stream its code occupied. pub const Decoded = struct { symbol: u16, length: u8 }; /// Looks up the symbol whose code begins the next bits of the stream, `bits`, /// least significant first, of which `available` are known; any above that /// must be zero. Returns null if the code is longer than `available`. pub inline fn decode(table: []const Entry, bits: u64, available: u32) ?Decoded { const e = table[@as(usize, @truncate(bits)) & (root_size - 1)]; if (!e.link) { if (e.bits > available) return null; return .{ .symbol = e.value, .length = e.bits }; } const index = @as(usize, @truncate(bits >> root_bits)) & ((@as(usize, 1) << @intCast(e.bits)) - 1); const s = table[e.value + index]; const length = root_bits + s.bits; if (length > available) return null; return .{ .symbol = s.value, .length = length }; } fn reverse(code: u32, len: u8) usize { return @as(usize, @bitReverse(@as(u16, @intCast(code)))) >> @intCast(16 - @as(u5, @intCast(len))); } test "assignCodes reproduces the example in RFC 1951 §3.2.2" { // Lengths (3, 3, 3, 3, 3, 2, 4, 4) for symbols A..H. const lengths = [_]u8{ 3, 3, 3, 3, 3, 2, 4, 4 }; var codes: [8]u16 = undefined; assignCodes(&lengths, &codes); try std.testing.expectEqualSlices(u16, &.{ 0b010, 0b011, 0b100, 0b101, 0b110, 0b00, 0b1110, 0b1111 }, &codes); } fn expectDecodes(table: []const Entry, lengths: []const u8) !void { var codes: [format.num_command_symbols]u16 = undefined; assignCodes(lengths, &codes); for (lengths, 0..) |l, sym| { if (l == 0) continue; // The code as it appears in the stream: most significant bit first. const bits: u64 = reverse(codes[sym], l); const d = decode(table, bits, max_length) orelse return error.TestUnexpectedResult; try std.testing.expectEqual(sym, d.symbol); try std.testing.expectEqual(l, d.length); // Not enough bits yet: no answer rather than a wrong one. if (l > 0) try std.testing.expectEqual(null, decode(table, bits, l - 1)); } } test "build: short codes, long codes and a single symbol" { const gpa = std.testing.allocator; var table: std.ArrayList(Entry) = .empty; defer table.deinit(gpa); const short = [_]u8{ 3, 3, 3, 3, 3, 2, 4, 4 }; try build(gpa, &table, &short); try expectDecodes(table.items, &short); // A skewed code reaching the full 15 bits: lengths 1, 2, ..., 14, 15, 15. var long: [16]u8 = undefined; for (0..15) |i| long[i] = @intCast(i + 1); long[15] = 15; table.clearRetainingCapacity(); try build(gpa, &table, &long); try expectDecodes(table.items, &long); // Second-level tables of three sizes: 120 eight-bit codes, then 268 // nine-bit codes in pairs under 134 prefixes, then a prefix holding four // ten-bit codes and one holding eight eleven-bit codes. var mixed: [402]u8 = undefined; @memset(mixed[0..120], 8); @memset(mixed[120..388], 9); @memset(mixed[388..392], 10); @memset(mixed[392..400], 11); // Two unused symbols, which must not disturb anything. @memset(mixed[400..402], 0); table.clearRetainingCapacity(); try build(gpa, &table, &mixed); try expectDecodes(table.items, &mixed); const single = [_]u8{ 0, 0, 7, 0 }; table.clearRetainingCapacity(); try build(gpa, &table, &single); const d = decode(table.items, 0xabcd, 0).?; try std.testing.expectEqual(2, d.symbol); try std.testing.expectEqual(0, d.length); } test "lengthsFromCounts makes complete codes within the limit" { var lengths: [format.num_command_symbols]u8 = undefined; // Fibonacci counts make the deepest possible Huffman tree. var fib: [30]u32 = undefined; fib[0] = 1; fib[1] = 1; for (2..fib.len) |i| fib[i] = fib[i - 1] + fib[i - 2]; for ([_]u4{ 5, 7, 15 }) |limit| { try std.testing.expectEqual(fib.len, lengthsFromCounts(&fib, limit, &lengths)); var kraft: u64 = 0; for (lengths[0..fib.len]) |l| { try std.testing.expect(l >= 1 and l <= limit); kraft += @as(u64, 1) << @intCast(15 - l); } try std.testing.expectEqual(1 << 15, kraft); } // Commoner symbols never get longer codes. for (fib[0 .. fib.len - 1], fib[1..], lengths[0 .. fib.len - 1], lengths[1..fib.len]) |ca, cb, la, lb| { if (ca < cb) try std.testing.expect(la >= lb); } const gpa = std.testing.allocator; var table: std.ArrayList(Entry) = .empty; defer table.deinit(gpa); var counts: [format.num_command_symbols]u32 = undefined; var prng: std.Random.DefaultPrng = .init(1); for (0..50) |_| { const n = prng.random().intRangeAtMost(usize, 2, counts.len); for (counts[0..n]) |*c| c.* = if (prng.random().boolean()) 0 else prng.random().int(u16); counts[0] = 1; counts[1] = 1; _ = lengthsFromCounts(counts[0..n], 15, &lengths); table.clearRetainingCapacity(); try build(gpa, &table, lengths[0..n]); try expectDecodes(table.items, lengths[0..n]); } try std.testing.expectEqual(1, lengthsFromCounts(&.{ 0, 7, 0 }, 15, &lengths)); try std.testing.expectEqualSlices(u8, &.{ 0, 0, 0 }, lengths[0..3]); } test "build rejects codes that are not complete" { const gpa = std.testing.allocator; var table: std.ArrayList(Entry) = .empty; defer table.deinit(gpa); try std.testing.expectError(error.InvalidPrefixCode, build(gpa, &table, &.{ 1, 2 })); try std.testing.expectError(error.InvalidPrefixCode, build(gpa, &table, &.{ 1, 1, 1 })); try std.testing.expectError(error.InvalidPrefixCode, build(gpa, &table, &.{ 0, 0 })); }