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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Optimal parsing: choosing a meta-block's literals and copies by the//! cheapest path through it, rather than taking the best-looking match at//! each position as it comes.//!//! Every position is a node, and the cost of reaching it is the fewest bits//! that can encode everything before it. From each node there is a step to//! the next position for a literal, and a step to every position a copy//! from here could end at, for every candidate distance and every length up//! to its longest. A step is priced by a cost model, an estimate of what//! each symbol will cost once the prefix codes are built: the first pass//! guesses, and each further pass prices by the symbols the previous pass//! chose. The cheapest path to the end is the parse.//!//! The four most recent distances, which the format writes almost for free,//! depend on the path taken to a node, so each node carries its own and//! tries them as candidates of its own. This is the approach of the//! reference compressor's top two qualities, which it calls Zopfli after the//! deflate compressor it first appeared in.
const std = @import("std");const Allocator = std.mem.Allocator;
const format = @import("format.zig");
/// A copy the match finder found at a position: the longest it can be at/// this distance, or a static dictionary word, which has only the one/// length.pub const Candidate = struct { /// How many bytes of input it covers. length: u32, distance: u32, /// For a dictionary word, the length of the base word; zero for a /// backward copy. word_length: u8 = 0,};
/// One step of the chosen path: some literals, then a copy, or with/// `length` zero, only literals, which is how a meta-block ends.pub const Step = struct { insert_len: u32, length: u32, distance: u32, word_length: u8,};
/// Copies longer than this are not tried at every length; a copy that/// reaches further is taken whole.pub const max_length = 325;
/// What each symbol is expected to cost, in bits.pub const CostModel = struct { literal: [format.num_literal_symbols]f32, command: [format.num_command_symbols]f32, distance: [format.max_distance_symbols]f32,
/// The first guess: literals by how often each byte appears in the /// block, and shorter commands and distances somewhat cheaper than /// longer ones, as the reference compressor starts. pub fn initial(m: *CostModel, data: []const u8) void { var counts: [format.num_literal_symbols]u32 = @splat(0); for (data) |b| counts[b] += 1; fromCounts(&m.literal, &counts); for (&m.command, 0..) |*c, i| c.* = @log2(@as(f32, @floatFromInt(11 + i))); for (&m.distance, 0..) |*c, i| c.* = @log2(@as(f32, @floatFromInt(20 + i))); }
/// Costs from what a parse used. pub fn fromParse(m: *CostModel, literal: []const u32, command: []const u32, distance: []const u32) void { fromCounts(&m.literal, literal); fromCounts(&m.command, command); fromCounts(&m.distance, distance); }
fn fromCounts(out: []f32, counts: []const u32) void { var total: u64 = 0; for (counts) |c| total += c; const log_total = @log2(@as(f32, @floatFromInt(@max(total, 1)))); for (out, counts) |*o, c| { // A symbol not yet used is not free: price it a little above // the rarest that was. o.* = if (c == 0) log_total + 2 else log_total - @log2(@as(f32, @floatFromInt(c))); } }};
const Node = struct { cost: f32, /// How the cheapest path got here: a copy of this many bytes, or zero /// for a literal. length: u32, distance: u32, word_length: u8, /// Literals since the last copy on that path. literals: u32, /// The four most recent distances at this point on that path. ring: [4]u32,};
/// Working space, kept between meta-blocks.pub const State = struct { /// The candidates of every position, back to back, and where each /// position's start. candidates: std.ArrayList(Candidate) = .empty, offsets: std.ArrayList(u32) = .empty, /// Whether each position is inside a copy too long to try length by /// length, which is taken whole: such a position is passed through by /// literals but tries no copies of its own. inside: std.ArrayList(bool) = .empty, nodes: std.ArrayList(Node) = .empty, steps: std.ArrayList(Step) = .empty,
pub fn deinit(s: *State, gpa: Allocator) void { s.candidates.deinit(gpa); s.offsets.deinit(gpa); s.inside.deinit(gpa); s.nodes.deinit(gpa); s.steps.deinit(gpa); s.* = undefined; }
/// Starts gathering candidates for a new meta-block. pub fn begin(s: *State) void { s.candidates.clearRetainingCapacity(); s.offsets.clearRetainingCapacity(); s.inside.clearRetainingCapacity(); }
/// Ends the candidates of one position and starts the next. pub fn endPosition(s: *State, gpa: Allocator, inside: bool) Allocator.Error!void { try s.offsets.append(gpa, @intCast(s.candidates.items.len)); try s.inside.append(gpa, inside); }
fn candidatesAt(s: *const State, i: usize) []const Candidate { const from = if (i == 0) 0 else s.offsets.items[i - 1]; return s.candidates.items[from..s.offsets.items[i]]; }};
/// The short distance code for `distance` given the recent distances/// `ring`, if there is one (RFC 7932 §4).pub fn shortCode(ring: [4]u32, distance: u32) ?u16 { for (ring, 0..) |d, k| { if (d == distance) return @intCast(k); } const deltas = [6]i64{ -1, 1, -2, 2, -3, 3 }; for (deltas, 0..) |delta, k| { if (@as(i64, ring[0]) + delta == distance) return @intCast(4 + k); if (@as(i64, ring[1]) + delta == distance) return @intCast(10 + k); } return null;}
/// How a copy is written, given the literals before it and the recent/// distances: the command symbol, and the distance code if one is written.pub const Encoding = struct { symbol: u16, distance: ?format.DistanceCode,};
pub fn encoding(insert_len: u32, copy_len: u32, distance: u32, dictionary: bool, ring: [4]u32) Encoding { const insert_code = format.insertLengthCode(insert_len); const copy_code = format.copyLengthCode(copy_len); // A dictionary word is always written out in full, since the // decompressor does not remember dictionary distances. const short: ?u16 = if (dictionary) null else shortCode(ring, distance); if (short == 0 and insert_code < 8 and copy_code < 16) { return .{ .symbol = format.commandSymbol(insert_code, copy_code, true), .distance = null }; } const dc: format.DistanceCode = if (short) |sc| .{ .code = sc, .extra_bits = 0, .extra = 0 } else format.distanceCode(distance, 0, 0); return .{ .symbol = format.commandSymbol(insert_code, copy_code, false), .distance = dc };}
/// The recent distances after a copy written as `e`.pub fn pushed(ring: [4]u32, distance: u32, e: Encoding, dictionary: bool) [4]u32 { if (dictionary) return ring; const d = e.distance orelse return ring; if (d.code == 0) return ring; return .{ distance, ring[0], ring[1], ring[2] };}
fn stepCost(model: *const CostModel, insert_len: u32, copy_len: u32, e: Encoding) f32 { const parts = format.command(e.symbol); const ins = format.insert_length_codes[parts.insert_code]; const cpy = format.copy_length_codes[parts.copy_code]; _ = insert_len; _ = copy_len; var c = model.command[e.symbol] + @as(f32, @floatFromInt(@as(u32, ins.extra_bits) + cpy.extra_bits)); if (e.distance) |d| c += model.distance[d.code] + @as(f32, @floatFromInt(d.extra_bits)); return c;}
/// Finds the cheapest path through `data[start..end]` under `model`, using/// the candidates gathered into `state` for each position, and leaves it in/// `state.steps`. `ring` is the recent distances at `start`, and copies may/// reach no further back than `max_backward`.pub fn shortestPath(gpa: Allocator, state: *State, data: []const u8, start: usize, end: usize, ring: [4]u32, max_backward: u32, model: *const CostModel) Allocator.Error!void { const n = end - start; std.debug.assert(state.offsets.items.len == n); try state.nodes.resize(gpa, n + 1); const nodes = state.nodes.items; for (nodes) |*node| node.cost = std.math.inf(f32); nodes[0] = .{ .cost = 0, .length = 0, .distance = 0, .word_length = 0, .literals = 0, .ring = ring };
for (0..n) |i| { const here = nodes[i]; if (here.cost == std.math.inf(f32)) continue; const pos = start + i;
// A literal. { const c = here.cost + model.literal[data[pos]]; const next = &nodes[i + 1]; if (c < next.cost) next.* = .{ .cost = c, .length = 0, .distance = 0, .word_length = 0, .literals = here.literals + 1, .ring = here.ring }; }
if (state.inside.items[i]) continue; const room: u32 = @intCast(n - i); // The recent distances on this path, at every length from 2. for (here.ring) |d| { if (d > pos or d > max_backward) continue; const longest = matchLength(data, pos - d, pos, @min(room, max_length)); if (longest >= 2) relaxLengths(nodes, model, i, d, 2, longest); } // The match finder's candidates: each reaches further than the one // before, at a greater distance, so each is tried only at the // lengths the ones before could not reach. var reached: u32 = 3; for (state.candidatesAt(i)) |cand| { if (cand.word_length != 0) { relax(nodes, model, i, cand.length, cand.distance, cand.word_length); continue; } const top = @min(cand.length, max_length); if (top > reached) relaxLengths(nodes, model, i, cand.distance, reached + 1, top); // Longer than is worth trying length by length: only whole. if (cand.length > max_length) relax(nodes, model, i, cand.length, cand.distance, 0); reached = @max(reached, top); } }
// Back from the end, then turned round. state.steps.clearRetainingCapacity(); var i = n; var literals: u32 = 0; while (i > 0) { const node = nodes[i]; if (node.length == 0) { literals += 1; i -= 1; continue; } // The literals counted so far follow this copy; record them in the // step after it once its own literals are known. try state.steps.append(gpa, .{ .insert_len = literals, .length = node.length, .distance = node.distance, .word_length = node.word_length }); literals = 0; i -= node.length; } // Each step was recorded with the literals after it; shift them so each // carries the literals before it, and end with the trailing ones. std.mem.reverse(Step, state.steps.items); var before = literals; for (state.steps.items) |*step| { const after = step.insert_len; step.insert_len = before; before = after; } if (before > 0) try state.steps.append(gpa, .{ .insert_len = before, .length = 0, .distance = 0, .word_length = 0 });}
/// The copy length code of every length up to `max_length`.const copy_codes = blk: { @setEvalBranchQuota(100_000); var codes: [max_length + 1]u5 = undefined; codes[0] = 0; codes[1] = 0; for (2..max_length + 1) |len| codes[len] = format.copyLengthCode(len); break :blk codes;};
/// Tries a backward copy from node `i` at distance `distance`, at every/// length from `lo` to `hi`. Everything but the copy length code is the/// same at every length, so it is worked out once.fn relaxLengths(nodes: []Node, model: *const CostModel, i: usize, distance: u32, lo: u32, hi: u32) void { std.debug.assert(hi <= max_length); const here = nodes[i]; const insert_code = format.insertLengthCode(here.literals); const insert_bits: f32 = @floatFromInt(format.insert_length_codes[insert_code].extra_bits); const short = shortCode(here.ring, distance); const dc: format.DistanceCode = if (short) |sc| .{ .code = sc, .extra_bits = 0, .extra = 0 } else format.distanceCode(distance, 0, 0); const distance_cost = model.distance[dc.code] + @as(f32, @floatFromInt(dc.extra_bits)); const ring_after: [4]u32 = if (dc.code == 0) here.ring else .{ distance, here.ring[0], here.ring[1], here.ring[2] }; const base = here.cost + insert_bits; var len = lo; while (len <= hi) : (len += 1) { const copy_code = copy_codes[len]; const implicit = short == 0 and insert_code < 8 and copy_code < 16; const symbol = format.commandSymbol(insert_code, copy_code, implicit); var c = base + model.command[symbol] + @as(f32, @floatFromInt(format.copy_length_codes[copy_code].extra_bits)); if (!implicit) c += distance_cost; const next = &nodes[i + len]; if (c < next.cost) next.* = .{ .cost = c, .length = len, .distance = distance, .word_length = 0, .literals = 0, .ring = ring_after, }; }}
fn relax(nodes: []Node, model: *const CostModel, i: usize, length: u32, distance: u32, word_length: u8) void { const here = &nodes[i]; const dictionary = word_length != 0; const copy_len = if (dictionary) word_length else length; const e = encoding(here.literals, copy_len, distance, dictionary, here.ring); const c = here.cost + stepCost(model, here.literals, copy_len, e); const next = &nodes[i + length]; if (c < next.cost) next.* = .{ .cost = c, .length = length, .distance = distance, .word_length = word_length, .literals = 0, .ring = pushed(here.ring, distance, e, dictionary), };}
fn matchLength(data: []const u8, a: usize, b: usize, max: u32) u32 { var n: u32 = 0; while (n + 8 <= max) : (n += 8) { const x = std.mem.readInt(u64, data[a + n ..][0..8], .little) ^ std.mem.readInt(u64, data[b + n ..][0..8], .little); if (x != 0) return n + @ctz(x) / 8; } while (n < max and data[a + n] == data[b + n]) n += 1; return n;}
test "shortCode and encoding agree with the format" { const ring = [4]u32{ 10, 20, 30, 40 }; try std.testing.expectEqual(0, shortCode(ring, 10)); try std.testing.expectEqual(3, shortCode(ring, 40)); try std.testing.expectEqual(4, shortCode(ring, 9)); try std.testing.expectEqual(15, shortCode(ring, 23)); try std.testing.expectEqual(null, shortCode(ring, 1000)); // The last distance, with a short insert and copy, needs no distance // code at all. try std.testing.expectEqual(null, encoding(3, 5, 10, false, ring).distance); try std.testing.expectEqual(ring, pushed(ring, 10, encoding(3, 5, 10, false, ring), false)); const far = encoding(3, 5, 1000, false, ring); try std.testing.expectEqual([4]u32{ 1000, 10, 20, 30 }, pushed(ring, 1000, far, false)); try std.testing.expectEqual(ring, pushed(ring, 1000, encoding(3, 5, 1000, true, ring), true));}