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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A streaming Brotli compressor that does no I/O.//!//! The counterpart of `Decompressor`, driven the same way: each call to//! `compress` takes whatever uncompressed bytes the caller has and whatever//! room it has for output, and reports how much of each it used and why it//! stopped. The third argument says what the caller wants done://!//! * `.process`: take the input and compress what is ready. Input is//! gathered into blocks, so output may lag well behind it.//! * `.flush`: also compress everything taken so far and carry the stream//! to a byte boundary, so that a decompressor given the output so far can//! produce all of the input so far.//! * `.finish`: also end the stream.//!//! ```//! var c: brotli.Compressor = .init(gpa, .{ .quality = 6 }); defer c.deinit();//! while (true) { const r = try c.compress(input, output, if (more) .process//! else .finish); input = input[r.read..]; consume(output[0..r.written]);//! switch (r.status) { .done => break, .need_input => input = try readMore(),//! .need_output => {}, } }//! ```//!//! # How it compresses//!//! Input is cut into meta-blocks of 64 KiB to 256 KiB. Each is parsed into//! literals and backward copies by a match finder that searches harder and//! further at higher qualities: hash chains up to quality 5, and from//! quality 6 a binary tree, which finds the longest matches by visiting a//! few dozen earlier positions rather than hundreds. From quality 4 the//! parse looks one byte ahead before committing to a match. Copies that reuse one of the//! four most recent distances are written with the short codes the format//! has for them.//!//! From quality 4 the parse also looks up the static dictionary, under the//! 86 transforms that leave the start of a word in place, and the literals//! use context modeling: the context mode that suits them best, and as many//! as 8 to 32 literal codes, each shared by the contexts whose statistics//! are alike.//!//! From quality 7 each of the meta-block's three streams — literals,//! commands and distances — may be split into blocks of different types//! with codes of their own (see `MetaBlockEncoder`), where the statistics//! change part way through.//!//! At quality 10 and 11 the parse is optimal rather than greedy: the//! cheapest path through the meta-block under a model of what each symbol//! will cost, refined over two or three passes (see `optimal_parse`).//!//! Every one of these is used only where it pays for itself. A meta-block//! that would come out larger than its input is written uncompressed//! instead, so incompressible data costs a few bytes per meta-block and no//! more.//!//! # Memory//!//! The compressor keeps up to a window of past input to find copies in,//! plus the block being gathered, and hash tables whose size grows with the//! quality: about 64 KiB at quality 0, and 8.5 MiB at quality 9 and above,//! though never much bigger than an input compressed in one go. From quality//! 4 there is 64 KiB of working space for context modeling, and at quality//! 10 and 11 the optimal parse needs about 40 bytes for each byte of the//! meta-block. The static dictionary's index, 118 KiB, is built once and//! shared by every compressor in the process. All of it is allocated as it is first needed.
const std = @import("std");const Allocator = std.mem.Allocator;const Io = std.Io;
const BitWriter = @import("BitWriter.zig");const DictionaryIndex = @import("DictionaryIndex.zig");const MetaBlockEncoder = @import("MetaBlockEncoder.zig");const format = @import("format.zig");const optimal_parse = @import("optimal_parse.zig");const store = @import("store.zig");const stream = @import("stream.zig");
const Compressor = @This();
pub const Options = struct { /// From 0, fastest, to 11, smallest. The levels are this compressor's /// own; they do not produce the same output as the reference /// compressor's levels of the same number. quality: u4 = default_quality, /// The window, as log2 of its size in bytes, from 10 to 24: how far /// back a copy may reach, and how much memory a decompressor needs to /// follow it. A larger window finds more copies in a long input. window_bits: u5 = 22,};
pub const default_quality = 6;pub const max_quality = 11;
/// What `compress` should do once it has taken the input it is given.pub const Operation = enum { /// Compress what is ready, and keep the rest for later. process, /// Compress everything given so far and carry the output to a byte /// boundary. flush, /// Compress everything and end the stream. finish,};
pub const Error = error{ /// Input was given after the stream was finished. StreamFinished,} || Allocator.Error;
pub const Status = stream.Status;pub const Result = stream.Result;
/// The shortest copy the match finder looks for.const min_match = 4;
/// How a quality level searches.const Params = struct { /// log2 of the number of hash buckets. hash_bits: u5, /// log2 of how many past positions the hash chains link, or 0 for one /// candidate per bucket and no chains. chain_bits: u5, /// How many candidates to try at each position. max_chain: u32, /// A match this long is taken without looking for a longer one. nice_length: u32, /// Look one byte ahead for a better match before taking one. lazy: bool, /// After a run of positions without a match, skip ahead faster. skip: bool, /// Insert every position inside a match into the hash table, rather /// than only the first few. insert_all: bool, /// log2 of the meta-block size. block_bits: u5, /// The most literal codes context modeling may use; 1 for none. literal_trees: u16, /// Look for static dictionary words, where the best copy found is /// shorter than `dictionary_below`. dictionary: bool, dictionary_below: u32, /// Divide each meta-block's streams into blocks of different types. block_split: bool, /// How many passes of optimal parsing, each costed by the one before; /// 0 for the greedy, lazy parse. optimal_passes: u2, /// Find matches with a binary tree rather than hash chains, searching /// `max_chain` deep. tree: bool,};
const params_by_quality = [max_quality + 1]Params{ .{ .hash_bits = 14, .chain_bits = 0, .max_chain = 1, .nice_length = 32, .lazy = false, .skip = true, .insert_all = false, .block_bits = 16, .literal_trees = 1, .dictionary = false, .dictionary_below = 0, .block_split = false, .optimal_passes = 0, .tree = false }, .{ .hash_bits = 15, .chain_bits = 0, .max_chain = 1, .nice_length = 64, .lazy = false, .skip = true, .insert_all = false, .block_bits = 16, .literal_trees = 1, .dictionary = false, .dictionary_below = 0, .block_split = false, .optimal_passes = 0, .tree = false }, .{ .hash_bits = 15, .chain_bits = 16, .max_chain = 4, .nice_length = 64, .lazy = false, .skip = false, .insert_all = false, .block_bits = 16, .literal_trees = 1, .dictionary = false, .dictionary_below = 0, .block_split = false, .optimal_passes = 0, .tree = false }, .{ .hash_bits = 16, .chain_bits = 16, .max_chain = 8, .nice_length = 64, .lazy = false, .skip = false, .insert_all = false, .block_bits = 16, .literal_trees = 1, .dictionary = false, .dictionary_below = 0, .block_split = false, .optimal_passes = 0, .tree = false }, .{ .hash_bits = 16, .chain_bits = 17, .max_chain = 16, .nice_length = 128, .lazy = true, .skip = false, .insert_all = true, .block_bits = 18, .literal_trees = 8, .dictionary = true, .dictionary_below = 1, .block_split = false, .optimal_passes = 0, .tree = false }, .{ .hash_bits = 16, .chain_bits = 17, .max_chain = 32, .nice_length = 128, .lazy = true, .skip = false, .insert_all = true, .block_bits = 18, .literal_trees = 16, .dictionary = true, .dictionary_below = 6, .block_split = false, .optimal_passes = 0, .tree = false }, .{ .hash_bits = 16, .chain_bits = 18, .max_chain = 64, .nice_length = 192, .lazy = true, .skip = false, .insert_all = true, .block_bits = 18, .literal_trees = 16, .dictionary = true, .dictionary_below = 8, .block_split = false, .optimal_passes = 0, .tree = true }, .{ .hash_bits = 17, .chain_bits = 18, .max_chain = 128, .nice_length = 256, .lazy = true, .skip = false, .insert_all = true, .block_bits = 18, .literal_trees = 16, .dictionary = true, .dictionary_below = 12, .block_split = true, .optimal_passes = 0, .tree = true }, .{ .hash_bits = 17, .chain_bits = 18, .max_chain = 256, .nice_length = 512, .lazy = true, .skip = false, .insert_all = true, .block_bits = 18, .literal_trees = 32, .dictionary = true, .dictionary_below = 38, .block_split = true, .optimal_passes = 0, .tree = true }, .{ .hash_bits = 17, .chain_bits = 20, .max_chain = 512, .nice_length = 1024, .lazy = true, .skip = false, .insert_all = true, .block_bits = 18, .literal_trees = 32, .dictionary = true, .dictionary_below = 38, .block_split = true, .optimal_passes = 0, .tree = true }, .{ .hash_bits = 17, .chain_bits = 20, .max_chain = 32, .nice_length = 1024, .lazy = true, .skip = false, .insert_all = true, .block_bits = 18, .literal_trees = 32, .dictionary = true, .dictionary_below = 38, .block_split = true, .optimal_passes = 2, .tree = true }, .{ .hash_bits = 17, .chain_bits = 20, .max_chain = 64, .nice_length = 2048, .lazy = true, .skip = false, .insert_all = true, .block_bits = 18, .literal_trees = 32, .dictionary = true, .dictionary_below = 38, .block_split = true, .optimal_passes = 3, .tree = true },};
/// The smallest meta-block any quality gathers before compressing, which is/// what `maxCompressedSize` counts on.pub const min_block_size = 1 << 16;
const Command = MetaBlockEncoder.Command;
gpa: Allocator,options: Options,params: Params,state: enum { start, running, finished } = .start,bw: BitWriter = .{},/// How much of `bw.bytes` has been handed to the caller.out_pos: usize = 0,
/// Past input kept to find copies in, then the input not yet compressed.buf: std.ArrayList(u8) = .empty,/// How much of `buf` has been compressed.processed: usize = 0,/// The position in the stream of `buf.items[0]`.base: u64 = 0,/// Hash buckets, each the stream position, truncated to 32 bits, of the last/// position whose first four bytes hashed there; and for each position, the/// one before it in the same bucket. Positions are truncated freely because/// every candidate is checked against the data before it is used.head: []u32 = &.{},prev: []u32 = &.{},/// Positions below this have been put in the hash table.inserted: u64 = 0,/// Whether the hash tables have been sized for this stream, and log2 of/// the number of buckets they were given.tables_ready: bool = false,hash_bits: u5 = 0,/// The four most recent distances, most recent first, kept exactly as the/// decompressor will.last_distances: [4]u32 = .{ 4, 11, 15, 16 },commands: std.ArrayList(Command) = .empty,/// The static dictionary, indexed, at the qualities that search it.dictionary: ?*const DictionaryIndex = null,/// How often the dictionary has been looked up, and how often that found/// a word.dictionary_lookups: u32 = 0,dictionary_finds: u32 = 0,/// Chooses the coding of each meta-block and writes it.encoder: MetaBlockEncoder,/// Working space for optimal parsing.optimal: optimal_parse.State = .{},
/// Asserts that `options` are in range.pub fn init(gpa: Allocator, options: Options) Compressor { std.debug.assert(options.quality <= max_quality); std.debug.assert(options.window_bits >= format.min_window_bits and options.window_bits <= format.max_window_bits); return .{ .gpa = gpa, .options = options, .params = params_by_quality[options.quality], .encoder = .init(gpa) };}
pub fn deinit(c: *Compressor) void { c.bw.deinit(c.gpa); c.buf.deinit(c.gpa); c.gpa.free(c.head); c.gpa.free(c.prev); c.commands.deinit(c.gpa); c.encoder.deinit(); c.optimal.deinit(c.gpa); c.* = undefined;}
/// Readies the compressor for a new stream, keeping what it has allocated.pub fn reset(c: *Compressor) void { var bw = c.bw; bw.bytes.clearRetainingCapacity(); bw.acc = 0; bw.count = 0; var buf = c.buf; buf.clearRetainingCapacity(); var commands = c.commands; commands.clearRetainingCapacity(); c.* = .{ .gpa = c.gpa, .options = c.options, .params = c.params, .bw = bw, .buf = buf, .head = c.head, .prev = c.prev, .commands = commands, .dictionary = c.dictionary, .encoder = c.encoder, .optimal = c.optimal, };}
/// Whether the stream has been finished and every byte of it handed over.pub fn isDone(c: *const Compressor) bool { return c.state == .finished and c.out_pos == c.bw.bytes.items.len;}
/// Compresses as much of `input` into `output` as it can, then does what/// `op` asks.////// The result says how many bytes of `input` were consumed and how many of/// `output` were filled, and why it stopped:////// * `.need_input`: all of `input` was consumed, and what `op` asked is/// done: a `.flush` has been written out in full./// * `.need_output`: `output` is full. Call again with more room, the same/// `op`, and whatever of `input` was not consumed./// * `.done`: after `.finish`, the stream is complete and everything has/// been written.pub fn compress(c: *Compressor, input: []const u8, output: []u8, op: Operation) Error!Result { var read: usize = 0; var written: usize = 0; if (c.state == .finished and input.len > 0) return error.StreamFinished; if (c.state == .start) { try store.windowBits(&c.bw, c.gpa, c.options.window_bits); c.state = .running; } while (true) { written += c.drain(output[written..]); if (c.out_pos < c.bw.bytes.items.len) return .{ .read = read, .written = written, .status = .need_output }; if (c.state == .finished) return .{ .read = read, .written = written, .status = .done };
read += try c.absorb(input[read..]); if (c.buf.items.len - c.processed == c.blockSize()) { try c.compressBlock(false); continue; } if (read < input.len) continue;
switch (op) { .process => return .{ .read = read, .written = written, .status = .need_input }, .flush => { if (c.processed < c.buf.items.len) { try c.compressBlock(false); } else if (c.bw.count != 0) { try store.emptyMetadata(&c.bw, c.gpa); } else { return .{ .read = read, .written = written, .status = .need_input }; } }, .finish => { if (c.processed < c.buf.items.len) try c.compressBlock(true); try store.lastEmpty(&c.bw, c.gpa); c.state = .finished; }, } }}
/// Like `compress`, but writes into `w`, handing it at most `limit` bytes.////// The output goes straight into `w`'s buffer, which is drained first if it/// is full. A writer with no buffer at all is written through a small buffer/// on the stack instead. A result with `.need_output` means `limit` was/// reached.pub fn compressToWriter(c: *Compressor, input: []const u8, w: *Io.Writer, limit: Io.Limit, op: Operation) (Error || Io.Writer.Error)!Result { if (w.buffer.len == 0) { var scratch: [4096]u8 = undefined; const r = try c.compress(input, limit.slice(&scratch), op); try w.writeAll(scratch[0..r.written]); return r; } const r = try c.compress(input, limit.slice(try w.writableSliceGreedy(1)), op); w.advance(r.written); return r;}
/// The most bytes compressing `length` bytes in one go can produce, with/// `.finish` and no `.flush` along the way: the input stored as it is, plus/// a few bytes of framing for each meta-block.pub fn maxCompressedSize(length: usize) usize { return length + 5 * (length / min_block_size + 1) + 2;}
fn blockSize(c: *const Compressor) usize { return @as(usize, 1) << c.params.block_bits;}
fn maxDistance(c: *const Compressor) u32 { return format.maxBackwardDistance(c.options.window_bits);}
/// Hands over as much of the compressed output as `out` has room for.fn drain(c: *Compressor, out: []u8) usize { const pending = c.bw.bytes.items[c.out_pos..]; const n = @min(pending.len, out.len); @memcpy(out[0..n], pending[0..n]); c.out_pos += n; if (c.out_pos == c.bw.bytes.items.len) { c.bw.bytes.clearRetainingCapacity(); c.out_pos = 0; } return n;}
/// Takes as much of `input` as fits in the block being gathered, first/// dropping past input that has fallen out of the window if room is needed.fn absorb(c: *Compressor, input: []const u8) Allocator.Error!usize { const pending = c.buf.items.len - c.processed; const n = @min(input.len, c.blockSize() - pending); if (n == 0) return 0; const history = c.maxDistance(); if (c.buf.items.len + n > history + c.blockSize() and c.processed > history) { const drop = c.processed - history; const keep = c.buf.items[drop..]; std.mem.copyForwards(u8, c.buf.items[0..keep.len], keep); c.buf.shrinkRetainingCapacity(keep.len); c.processed -= drop; c.base += drop; } try c.buf.appendSlice(c.gpa, input[0..n]); return n;}
/// Compresses everything gathered and not yet compressed into one/// meta-block./// `last` says the stream ends with this meta-block.fn compressBlock(c: *Compressor, last: bool) Allocator.Error!void { const data = c.buf.items; const start = c.processed; const end = data.len; std.debug.assert(end > start); const saved_distances = c.last_distances; if (!c.tables_ready) { // A stream that is all here at once needs hash tables no bigger // than itself, which matters to a program compressing many small // things. try c.ensureTables(if (last and c.base == 0) end else null); c.tables_ready = true; }
c.commands.clearRetainingCapacity(); if (c.params.optimal_passes > 0) { try c.parseOptimal(start, end); } else { try c.parse(start, end); }
const bw = &c.bw; const mark = bw.mark(); const start_bits = bw.bitLength(); const start_bit = bw.count; var options: MetaBlockEncoder.Options = .{ .literal_trees = c.params.literal_trees, .split = false }; try c.encoder.encode(bw, data, c.base, start, end, c.commands.items, options); if (c.params.block_split) { // Splitting is not always worth the switches; write it both ways // and keep the smaller. const plain_bits = bw.bitLength() - start_bits; bw.restore(mark); options.split = true; try c.encoder.encode(bw, data, c.base, start, end, c.commands.items, options); if (bw.bitLength() - start_bits > plain_bits) { bw.restore(mark); options.split = false; try c.encoder.encode(bw, data, c.base, start, end, c.commands.items, options); } }
if (bw.bitLength() - start_bits >= store.uncompressedMetaBlockBits(@intCast(end - start), start_bit)) { // Not worth it. The decompressor will not see the copies, so the // distances they would have pushed must not count either. bw.restore(mark); c.last_distances = saved_distances; try store.uncompressedMetaBlock(bw, c.gpa, data[start..end]); } c.processed = end;}
// Parsing.
const Match = struct { /// How many bytes of input the match covers. length: u32 = 0, distance: u32 = 0, score: u64 = 0, /// For a dictionary word, the length of the base word, which is what the /// command carries as its copy length; zero for a backward copy. word_length: u32 = 0,};
/// The reference compressor's way of weighing a longer match against a/// more distant one: a byte copied is worth about 4.2 bits, and every/// doubling of the distance costs about one.const literal_score = 135;const distance_score = 30;const base_score = 1920;/// How much better the match one byte on must be to put off a match for it.const lazy_margin = 175;
fn score(length: u32, distance: u32) u64 { return @as(u64, literal_score) * length + base_score - @as(u64, distance_score) * std.math.log2_int(u32, distance);}
/// Splits `buf.items[start..end]` into commands.fn parse(c: *Compressor, start: usize, end: usize) Allocator.Error!void { const p = c.params; var i = start; var lit_start = start; while (i + min_match <= end) { var m = try c.findMatch(i, end); if (m.length == 0) { // Incompressible stretches are crossed faster and faster, at // the lowest qualities. i += if (p.skip) 1 + ((i - lit_start) >> 6) else 1; continue; } if (p.lazy) { while (i + 1 + min_match <= end) { const next = try c.findMatch(i + 1, end); if (next.score <= m.score + lazy_margin) break; i += 1; m = next; } } try c.emit(@intCast(i - lit_start), m); const match_end = i + m.length; const insert_end = if (p.insert_all) match_end else @min(match_end, i + 16); // Positions skipped over may have fallen out of the buffer since. const first_uninserted: usize = if (c.inserted > c.base) @intCast(c.inserted - c.base) else 0; var j = @max(i + 1, first_uninserted); while (j < insert_end and j + min_match <= c.buf.items.len) : (j += 1) { if (p.tree) try c.treeSearch(j, end, false) else c.insert(j); } i = match_end; lit_start = i; } if (lit_start < end) try c.emit(@intCast(end - lit_start), .{});}
/// Splits `buf.items[start..end]` into commands by the cheapest path/// through it (see `optimal_parse`).fn parseOptimal(c: *Compressor, start: usize, end: usize) Allocator.Error!void { const gpa = c.gpa; const data = c.buf.items; const st = &c.optimal;
// Every position's candidates, gathered once, since the hash table can // only be walked forward. A copy too long to try length by length is // taken whole, and the positions inside it get no candidates of their // own. st.begin(); var skip_until = start; var skip_start = start; for (start..end) |i| { if (i >= skip_until and i + min_match <= end) { const before = st.candidates.items.len; try c.findCandidates(i, end); for (st.candidates.items[before..]) |cand| { if (cand.word_length == 0 and cand.length > optimal_parse.max_length) { skip_start = i; skip_until = i + cand.length; } } } else if (i + min_match <= c.buf.items.len and c.base + i >= c.inserted) { try c.treeSearch(i, end, false); } try st.endPosition(gpa, i < skip_until and i != skip_start); }
var model: optimal_parse.CostModel = undefined; model.initial(data[start..end]); var pass: usize = 0; while (true) { try optimal_parse.shortestPath(gpa, st, data, start, end, c.last_distances, c.maxDistance(), &model); pass += 1; if (pass == c.params.optimal_passes) break; // Price the next pass by what this one chose. var literal: [format.num_literal_symbols]u32 = @splat(0); var command: [format.num_command_symbols]u32 = @splat(0); var distance: [format.max_distance_symbols]u32 = @splat(0); var ring = c.last_distances; var pos = start; for (st.steps.items) |step| { for (data[pos..][0..step.insert_len]) |b| literal[b] += 1; pos += step.insert_len + step.length; if (step.length == 0) { const ic = format.insertLengthCode(step.insert_len); command[format.commandSymbol(ic, 0, ic < 8)] += 1; continue; } const dictionary = step.word_length != 0; const copy_len = if (dictionary) step.word_length else step.length; const e = optimal_parse.encoding(step.insert_len, copy_len, step.distance, dictionary, ring); command[e.symbol] += 1; if (e.distance) |d| distance[d.code] += 1; ring = optimal_parse.pushed(ring, step.distance, e, dictionary); } model.fromParse(&literal, &command, &distance); }
for (st.steps.items) |step| { try c.emit(step.insert_len, .{ .length = step.length, .distance = step.distance, .word_length = step.word_length }); }}
/// Gathers the candidates for position `i` of `buf` into `optimal`: the/// match finder's matches, each longer than the one before at a greater/// distance, and a static dictionary word. Also puts `i` in the binary tree.fn findCandidates(c: *Compressor, i: usize, end: usize) Allocator.Error!void { const st = &c.optimal; const before = st.candidates.items.len; try c.treeSearch(i, end, true);
// A match that is no longer than a nearer one is never worth its // distance: keep only those that reach further at each greater distance. const found = st.candidates.items[before..]; var kept: usize = found.len; var nearest: u32 = std.math.maxInt(u32); var k = found.len; while (k > 0) { k -= 1; if (found[k].distance < nearest) { nearest = found[k].distance; kept -= 1; found[kept] = found[k]; } } std.mem.copyForwards(optimal_parse.Candidate, found[0 .. found.len - kept], found[kept..]); st.candidates.shrinkRetainingCapacity(before + found.len - kept);
if (c.dictionary) |dict| { const data = c.buf.items; if (dict.find(data[i..end])) |w| { const reach: u32 = @intCast(@min(c.base + i, c.maxDistance())); try st.candidates.append(c.gpa, .{ .length = w.output_length, .distance = w.distance(reach), .word_length = @intCast(w.word_length) }); } }}
/// Puts position `i` of `buf` into the binary tree of positions sharing its/// hash, and with `collect`, records the matches found on the way down,/// each longer than the last, as candidates ending no later than `end`.////// The tree is the one the reference compressor's top qualities use, and/// LZMA's before it: positions ordered by the bytes that follow them, so/// that one descent both finds the longest matches and puts the new/// position where it belongs, the new position taking the old root's place./// Each node is a pair of slots in `prev`, for its left and right children,/// holding positions plus one so that zero can mean none.fn treeSearch(c: *Compressor, i: usize, end: usize, collect: bool) Allocator.Error!void { const data = c.buf.items; const tree = c.prev; const mask = tree.len / 2 - 1; // Comparisons look as far as the data goes, even past the block, so // that the tree's order does not depend on where blocks end. const avail: u32 = @intCast(@min(data.len - i, c.params.nice_length)); const report_max: u32 = @intCast(end - i); const limit: u32 = @min(c.maxDistance(), @as(u32, @intCast(mask))); const cur: u32 = @truncate(c.base + i); const h = hash(data[i..][0..4], c.hash_bits); var next = c.head[h]; c.head[h] = cur +% 1; c.inserted = c.base + i + 1;
var left_slot = 2 * (cur & mask); var right_slot = left_slot + 1; var left_len: u32 = 0; var right_len: u32 = 0; var best: u32 = min_match - 1; var depth = c.params.max_chain; while (true) { const d = cur -% (next -% 1); if (next == 0 or depth == 0 or d == 0 or d > i or d > limit) { tree[left_slot] = 0; tree[right_slot] = 0; return; } depth -= 1; const j = i - d; var len = @min(left_len, right_len); len += matchLength(data, j + len, i + len, avail - len); if (collect and len > best) { best = len; const reported = @min(len, report_max); if (reported >= min_match) try c.optimal.candidates.append(c.gpa, .{ .length = reported, .distance = d }); } const node = 2 * ((next -% 1) & mask); if (len >= avail) { // As long a match as is looked for: the new position replaces // this one, taking over its children. tree[left_slot] = tree[node]; tree[right_slot] = tree[node + 1]; return; } if (data[j + len] < data[i + len]) { tree[left_slot] = next; left_slot = node + 1; left_len = len; next = tree[node + 1]; } else { tree[right_slot] = next; right_slot = node; right_len = len; next = tree[node]; } }}
fn ensureTables(c: *Compressor, length: ?usize) Allocator.Error!void { const p = c.params; const fits: u5 = if (length) |n| @intCast(@max(10, std.math.log2_int_ceil(usize, @max(n, 1)) + 1)) else 31; c.hash_bits = @min(p.hash_bits, fits); const hash_len = @as(usize, 1) << c.hash_bits; if (c.head.len != hash_len) { c.gpa.free(c.head); c.head = &.{}; c.head = try c.gpa.alloc(u32, hash_len); } @memset(c.head, 0); var prev_len: usize = if (p.chain_bits == 0) 0 else @as(usize, 1) << @min(p.chain_bits, c.options.window_bits, fits); // A binary tree takes two slots a position, where chains take one. if (p.tree) prev_len *= 2; if (c.prev.len != prev_len) { c.gpa.free(c.prev); c.prev = &.{}; if (prev_len != 0) c.prev = try c.gpa.alloc(u32, prev_len); } if (p.dictionary) c.dictionary = DictionaryIndex.shared();}
fn dictionaryWorthLooking(c: *const Compressor) bool { return c.dictionary_lookups < 1024 or c.dictionary_finds >= c.dictionary_lookups >> 7;}
inline fn hash(bytes: *const [4]u8, bits: u5) usize { const v = std.mem.readInt(u32, bytes, .little); return @intCast((v *% 0x1E35A7BD) >> @intCast(32 - @as(u6, bits)));}
/// Puts position `i` of `buf` in the hash table.fn insert(c: *Compressor, i: usize) void { const pos: u32 = @truncate(c.base + i); const h = hash(c.buf.items[i..][0..4], c.hash_bits); if (c.prev.len != 0) c.prev[pos & (c.prev.len - 1)] = c.head[h]; c.head[h] = pos; c.inserted = c.base + i + 1;}
/// The best match for the bytes at position `i` of `buf`, ending no later/// than `end`: a backward copy or a static dictionary word. Also puts `i` in/// the hash table.fn findMatch(c: *Compressor, i: usize, end: usize) Allocator.Error!Match { const data = c.buf.items; const p = c.params; const max_length: u32 = @intCast(end - i); // The newest position in the bucket may be anywhere in the window; the // chain behind it only reaches as far back as `prev` has room for. const chain_limit: u32 = @min(c.maxDistance(), @as(u32, @intCast(c.prev.len -| 1))); var limit = c.maxDistance(); var best: Match = .{};
// Reusing a recent distance costs almost nothing to write, so it is // worth a little length. for (c.last_distances, 0..) |d, k| { if (d > i or d > c.maxDistance()) continue; const len = matchLength(data, i - d, i, max_length); if (len < min_match) continue; const s = @as(u64, literal_score) * len + base_score + @as(u64, if (k == 0) 15 else 0); if (s > best.score) best = .{ .length = len, .distance = d, .score = s }; }
if (p.tree) { // The tree is searched by putting the position in it, which can // only be done once. if (c.base + i >= c.inserted) { const found = &c.optimal.candidates; const before = found.items.len; try c.treeSearch(i, end, true); for (found.items[before..]) |cand| { const s = score(cand.length, cand.distance); if (s > best.score) best = .{ .length = cand.length, .distance = cand.distance, .score = s }; } found.shrinkRetainingCapacity(before); } return c.dictionaryMatch(i, end, best); }
const pos: u32 = @truncate(c.base + i); var candidate = c.head[hash(data[i..][0..4], c.hash_bits)]; if (c.base + i >= c.inserted) c.insert(i); var last: u32 = 0; var tries = p.max_chain; while (tries > 0) : (tries -= 1) { const d = pos -% candidate; if (d <= last or d > i or d > limit) break; last = d; const j = i - d; // A longer match must at least agree at the byte past the best so // far. if (best.length < max_length and data[j + best.length] == data[i + best.length]) { const len = matchLength(data, j, i, max_length); if (len >= min_match) { const s = score(len, d); if (s > best.score) { best = .{ .length = len, .distance = d, .score = s }; if (len >= p.nice_length or len == max_length) break; } } } if (c.prev.len == 0 or d > chain_limit) break; candidate = c.prev[candidate & (c.prev.len - 1)]; limit = chain_limit; }
return c.dictionaryMatch(i, end, best);}
/// `found`, or a static dictionary word that beats it.fn dictionaryMatch(c: *Compressor, i: usize, end: usize, found: Match) Match { const data = c.buf.items; var best = found; // Look in the dictionary only where the copy found is short, and at the // lower qualities only where none was, as the reference compressor // does; and stop looking in data where it almost never finds anything, // which binary data soon shows itself to be. if (c.dictionary != null and best.length < c.params.dictionary_below and c.dictionaryWorthLooking()) { const dict = c.dictionary.?; c.dictionary_lookups += 1; if (dict.find(data[i..end])) |w| { c.dictionary_finds += 1; // A dictionary reference is a distance past the furthest a copy // could reach from here (RFC 7932 §8). const reach: u32 = @intCast(@min(c.base + i, c.maxDistance())); const d = w.distance(reach); const s = score(w.output_length, d); if (s > best.score) best = .{ .length = w.output_length, .distance = d, .score = s, .word_length = w.word_length }; } } return best;}
/// How many bytes from `a` and `b` on agree, up to `max`.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;}
/// Adds a command inserting `insert_len` literals and then taking `m`, or,/// with `m` empty, the last command of a meta-block, which only inserts.fn emit(c: *Compressor, insert_len: u32, m: Match) Allocator.Error!void { const insert_code = format.insertLengthCode(insert_len); if (m.length == 0) { try c.commands.append(c.gpa, .{ .insert_len = insert_len, .copy_len = 0, .output_len = 0, .symbol = format.commandSymbol(insert_code, 0, insert_code < 8), .has_distance = false, .distance = undefined, }); return; } if (m.word_length != 0) { // A dictionary word: always written out in full, since the // decompressor does not remember dictionary distances. try c.commands.append(c.gpa, .{ .insert_len = insert_len, .copy_len = m.word_length, .output_len = m.length, .symbol = format.commandSymbol(insert_code, format.copyLengthCode(m.word_length), false), .has_distance = true, .distance = format.distanceCode(m.distance, 0, 0), }); return; } const copy_code = format.copyLengthCode(m.length); const short = c.shortCode(m.distance); if (short == 0 and insert_code < 8 and copy_code < 16) { try c.commands.append(c.gpa, .{ .insert_len = insert_len, .copy_len = m.length, .output_len = m.length, .symbol = format.commandSymbol(insert_code, copy_code, true), .has_distance = false, .distance = undefined, }); return; } const dc: format.DistanceCode = if (short) |s| .{ .code = s, .extra_bits = 0, .extra = 0 } else format.distanceCode(m.distance, 0, 0); if (dc.code != 0) { const ld = c.last_distances; c.last_distances = .{ m.distance, ld[0], ld[1], ld[2] }; } try c.commands.append(c.gpa, .{ .insert_len = insert_len, .copy_len = m.length, .output_len = m.length, .symbol = format.commandSymbol(insert_code, copy_code, false), .has_distance = true, .distance = dc, });}
/// The short distance code (RFC 7932 §4) that stands for `distance` given/// the recent distances, if there is one.fn shortCode(c: *const Compressor, distance: u32) ?u16 { const ld = c.last_distances; for (ld, 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, ld[0]) + delta == distance) return @intCast(4 + k); if (@as(i64, ld[1]) + delta == distance) return @intCast(10 + k); } return null;}