// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A streaming Brotli decompressor that does no I/O. //! //! The caller owns both ends. Each call to `decompress` takes whatever //! compressed bytes the caller has and whatever room it has for output, makes //! as much progress as those allow, and reports how much of each it used and //! why it stopped. Input may arrive a byte at a time and output may be drained //! a byte at a time; the decompressor keeps everything it needs to pick up //! exactly where it left off. //! //! ``` //! var d: brotli.Decompressor = .init(gpa, .{}); //! defer d.deinit(); //! while (true) { //! const r = try d.decompress(input, output); //! input = input[r.read..]; //! consume(output[0..r.written]); //! switch (r.status) { //! .done => break, //! .need_input => input = try readMore(), //! .need_output => {}, //! } //! } //! ``` //! //! # Memory //! //! The decompressor allocates its sliding window and its prefix code tables. //! The window grows as output is produced, up to the size the stream declares //! — at most 16 MiB — so a short stream costs little whatever window it //! declares. `Options.max_window_bits` refuses streams declaring more than a //! caller is willing to hold. The tables for one meta-block are a few hundred //! KiB at worst and are reused from one meta-block to the next. //! //! The `Decompressor` value itself is about 21 KiB, most of it the literal //! context map. //! //! # Errors //! //! Any error leaves the decompressor failed: every later call returns the same //! error until `reset`. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const BitReader = @import("BitReader.zig"); const context = @import("context.zig"); const dictionary = @import("dictionary.zig"); const format = @import("format.zig"); const prefix_code = @import("prefix_code.zig"); const transform = @import("transform.zig"); const stream = @import("stream.zig"); const Decompressor = @This(); pub const Options = struct { /// The largest window the decompressor will accept, as log2 of its size in /// bytes, from 10 to 24. A stream declaring a larger window fails with /// `error.WindowTooLarge` before anything is allocated for it. Every /// stream is accepted at the default, at a cost of up to 16 MiB. max_window_bits: u5 = format.max_window_bits, }; pub const Error = error{ /// The stream header declares a window size the format reserves. InvalidWindowSize, /// The stream declares a larger window than `Options.max_window_bits`. WindowTooLarge, /// A meta-block header has a reserved bit set or a length written with /// more nibbles or bytes than it needs. InvalidMetaBlockHeader, /// Bits the format requires to be zero, before a byte boundary, are not. InvalidPadding, /// A prefix code is malformed: a symbol out of range or repeated, or code /// lengths that do not make a complete code. InvalidPrefixCode, /// A context map's run of zeros runs past its end. InvalidContextMap, /// A distance resolves to zero or less. InvalidDistance, /// A reference to the static dictionary names a word length or a /// transform that does not exist. InvalidDictionaryReference, /// A meta-block's commands produce more bytes than its header declared. MetaBlockOverrun, } || Allocator.Error; pub const Status = stream.Status; pub const Result = stream.Result; const State = enum { window_bits, mb_last, mb_last_empty, mb_nibbles, mb_length, mb_uncompressed, metadata_header, metadata_length, metadata_skip, raw_copy, block_types, block_type_code, block_count_code, block_first_count, distance_params, context_modes, literal_trees_count, literal_context_map, distance_trees_count, distance_context_map, literal_codes, command_codes, distance_codes, command, command_extra, literals, distance, copy, dictionary_copy, mb_done, finish, flush, done, }; /// One of the three block categories: literals, insert-and-copy commands and /// distances. const Category = struct { types: u16 = 1, type_code: u32 = 0, count_code: u32 = 0, current: u16 = 0, previous: u16 = 1, remaining: u32 = format.unbounded_block_length, }; const cat_literal = 0; const cat_command = 1; const cat_distance = 2; /// Reading one prefix code, which may take many calls. const PrefixCodeReader = struct { stage: enum { idle, kind, simple_count, simple_symbols, code_lengths, symbols } = .idle, alphabet: u16 = 0, /// Where in `tables` this code's table will start. start: u32 = 0, index: u16 = 0, nsym: u8 = 0, symbols: [4]u16 = undefined, space: i32 = 0, num_codes: u8 = 0, code_lengths: [format.num_code_length_symbols]u8 = undefined, symbol: u16 = 0, prev_length: u8 = 0, repeat: u32 = 0, repeat_length: u8 = 0, lengths: [format.num_command_symbols]u8 = undefined, }; /// Reading one context map. const ContextMapReader = struct { stage: enum { rle, code, values, imtf } = .rle, rle_max: u8 = 0, code: u32 = 0, index: u32 = 0, }; gpa: Allocator, options: Options, state: State = .window_bits, failure: ?Error = null, br: BitReader = .{}, /// The sliding window, a power of two in size, holding the last /// `ring.len` bytes of output. It grows from small up to `1 << window_bits` /// and only wraps once it has reached that. ring: []u8 = &.{}, window_bits: u5 = 0, /// Bytes of output decoded so far, and of those, how many have been handed /// to the caller. pos: u64 = 0, flushed: u64 = 0, /// The caller's output buffer for the current call, and how much of it has /// been filled. out: []u8 = &.{}, out_pos: usize = 0, /// The four most recent distances, most recent first. last_distances: [4]u32 = .{ 4, 11, 15, 16 }, // The current meta-block. is_last: bool = false, nibbles: u8 = 0, /// Bytes still to come from this meta-block, or of metadata still to skip. remaining: u32 = 0, categories: [3]Category = .{ .{}, .{}, .{} }, category: u2 = 0, npostfix: u2 = 0, ndirect: u8 = 0, context_modes: [format.max_block_types]context.Mode = undefined, literal_trees: u16 = 0, distance_trees: u16 = 0, literal_map: [format.literal_contexts * format.max_block_types]u8 = undefined, distance_map: [format.distance_contexts * format.max_block_types]u8 = undefined, /// Every prefix code table for this meta-block, back to back. tables: std.ArrayList(prefix_code.Entry) = .empty, literal_codes: [format.max_block_types]u32 = undefined, command_codes: [format.max_block_types]u32 = undefined, distance_codes: [format.max_block_types]u32 = undefined, index: u16 = 0, pc: PrefixCodeReader = .{}, cm: ContextMapReader = .{}, /// A block switch half done: its type is read and its count is not. switch_pending: bool = false, // The current command. command: format.Command = undefined, insert_remaining: u32 = 0, copy_length: u32 = 0, distance: u32 = 0, copy_remaining: u32 = 0, word: [transform.max_word_length]u8 = undefined, word_len: u8 = 0, word_pos: u8 = 0, pub fn init(gpa: Allocator, options: Options) Decompressor { return .{ .gpa = gpa, .options = options }; } pub fn deinit(d: *Decompressor) void { d.gpa.free(d.ring); d.tables.deinit(d.gpa); d.* = undefined; } /// Readies the decompressor for a new stream, keeping what it has allocated. pub fn reset(d: *Decompressor) void { const gpa = d.gpa; const options = d.options; const ring = d.ring; var tables = d.tables; tables.clearRetainingCapacity(); d.* = .{ .gpa = gpa, .options = options, .ring = ring, .tables = tables }; } /// Whether the stream has ended and every byte of it has been handed over. pub fn isDone(d: *const Decompressor) bool { return d.state == .done; } /// Decompresses as much of `input` into `output` as it can. /// /// 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 more is needed. The bits /// of a partly read value are kept, so the next call starts from the next /// unread byte. /// * `.need_output`: `output` is full. Call again with more room, and with /// whatever of `input` was not consumed. /// * `.done`: the stream has ended and everything has been written. Bytes of /// `input` past the end of the stream are not consumed. pub fn decompress(d: *Decompressor, input: []const u8, output: []u8) Error!Result { if (d.failure) |e| return e; d.br.begin(input); d.out = output; d.out_pos = 0; var status = d.run() catch |e| { d.failure = e; return e; }; d.flushOut(); // Output the caller has no room for is the more pressing want. if (status == .need_input and d.flushed < d.pos) status = .need_output; // After `.need_input` every bit held is part of a value still being // read, so nothing can be given back; otherwise whole bytes drawn ahead // of need are returned, so that the caller sees exactly where the stream // ended. if (status != .need_input) d.br.unload(); const result: Result = .{ .read = d.br.pos, .written = d.out_pos, .status = status }; d.out = &.{}; d.br.begin(&.{}); return result; } /// Like `decompress`, 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 decompressToWriter(d: *Decompressor, input: []const u8, w: *Io.Writer, limit: Io.Limit) (Error || Io.Writer.Error)!Result { if (w.buffer.len == 0) { var scratch: [4096]u8 = undefined; const r = try d.decompress(input, limit.slice(&scratch)); try w.writeAll(scratch[0..r.written]); return r; } const r = try d.decompress(input, limit.slice(try w.writableSliceGreedy(1))); w.advance(r.written); return r; } fn run(d: *Decompressor) Error!Status { const br = &d.br; while (true) switch (d.state) { .window_bits => { const bits = readWindowBits(br) orelse return .need_input; if (bits == 0) return error.InvalidWindowSize; if (bits > d.options.max_window_bits) return error.WindowTooLarge; d.window_bits = bits; d.state = .mb_last; }, .mb_last => { d.is_last = (br.read(1) orelse return .need_input) == 1; d.state = if (d.is_last) .mb_last_empty else .mb_nibbles; }, .mb_last_empty => { const empty = br.read(1) orelse return .need_input; d.state = if (empty == 1) .mb_done else .mb_nibbles; }, .mb_nibbles => { const v = br.read(2) orelse return .need_input; if (v == 3) { d.state = .metadata_header; } else { d.nibbles = @intCast(v + 4); d.state = .mb_length; } }, .mb_length => { const bits: u32 = @as(u32, d.nibbles) * 4; const v = br.read(bits) orelse return .need_input; if (d.nibbles > 4 and v >> @intCast(bits - 4) == 0) return error.InvalidMetaBlockHeader; d.remaining = v + 1; d.state = if (d.is_last) .block_types else .mb_uncompressed; if (d.is_last) d.startHeader(); }, .mb_uncompressed => { const v = br.read(1) orelse return .need_input; if (v == 1) { if (br.alignToByte() != 0) return error.InvalidPadding; d.state = .raw_copy; } else { d.startHeader(); d.state = .block_types; } }, .metadata_header => { const v = br.read(3) orelse return .need_input; if (v & 1 != 0) return error.InvalidMetaBlockHeader; d.nibbles = @intCast(v >> 1); d.remaining = 0; d.state = .metadata_length; }, .metadata_length => { if (d.nibbles > 0) { const bits: u32 = @as(u32, d.nibbles) * 8; const v = br.read(bits) orelse return .need_input; if (d.nibbles > 1 and v >> @intCast(bits - 8) == 0) return error.InvalidMetaBlockHeader; d.remaining = v + 1; } if (br.alignToByte() != 0) return error.InvalidPadding; d.state = .metadata_skip; }, .metadata_skip => { while (d.remaining > 0) { if (br.count >= 8) { br.consume(8); d.remaining -= 1; } else { const skipped = br.takeBytes(d.remaining); if (skipped.len == 0) return .need_input; d.remaining -= @intCast(skipped.len); } } d.state = .mb_done; }, .raw_copy => { while (d.remaining > 0) { const room = try d.makeRoom(); if (room == 0) return .need_output; if (br.count >= 8) { d.put(br.readByte().?); d.remaining -= 1; continue; } const at = d.ringIndex(d.pos); const chunk = br.takeBytes(@min(room, d.remaining, d.ring.len - at)); if (chunk.len == 0) return .need_input; @memcpy(d.ring[at..][0..chunk.len], chunk); d.pos += chunk.len; d.remaining -= @intCast(chunk.len); } d.state = .mb_done; }, .block_types => { const v = readVarLenUint8(br) orelse return .need_input; const c = &d.categories[d.category]; c.* = .{ .types = v + 1 }; if (c.types >= 2) { d.startPrefixCode(c.types + 2); d.state = .block_type_code; } else { d.nextCategory(); } }, .block_type_code => { d.categories[d.category].type_code = try d.readPrefixCode() orelse return .need_input; d.startPrefixCode(format.num_block_count_symbols); d.state = .block_count_code; }, .block_count_code => { d.categories[d.category].count_code = try d.readPrefixCode() orelse return .need_input; d.state = .block_first_count; }, .block_first_count => { const c = &d.categories[d.category]; c.remaining = d.readBlockLength(c.count_code) orelse return .need_input; d.nextCategory(); }, .distance_params => { const v = br.read(6) orelse return .need_input; d.npostfix = @intCast(v & 3); d.ndirect = @as(u8, @intCast(v >> 2)) << d.npostfix; d.index = 0; d.state = .context_modes; }, .context_modes => { while (d.index < d.categories[cat_literal].types) : (d.index += 1) { const v = br.read(2) orelse return .need_input; d.context_modes[d.index] = @fromBackingInt(@intCast(v)); } d.state = .literal_trees_count; }, .literal_trees_count => { const v = readVarLenUint8(br) orelse return .need_input; d.literal_trees = v + 1; const size = format.literal_contexts * @as(usize, d.categories[cat_literal].types); if (d.literal_trees >= 2) { d.cm = .{}; d.state = .literal_context_map; } else { @memset(d.literal_map[0..size], 0); d.state = .distance_trees_count; } }, .literal_context_map => { const size = format.literal_contexts * @as(usize, d.categories[cat_literal].types); if (!try d.readContextMap(d.literal_map[0..size], d.literal_trees)) return .need_input; d.state = .distance_trees_count; }, .distance_trees_count => { const v = readVarLenUint8(br) orelse return .need_input; d.distance_trees = v + 1; const size = format.distance_contexts * @as(usize, d.categories[cat_distance].types); if (d.distance_trees >= 2) { d.cm = .{}; d.state = .distance_context_map; } else { @memset(d.distance_map[0..size], 0); d.index = 0; d.state = .literal_codes; } }, .distance_context_map => { const size = format.distance_contexts * @as(usize, d.categories[cat_distance].types); if (!try d.readContextMap(d.distance_map[0..size], d.distance_trees)) return .need_input; d.index = 0; d.state = .literal_codes; }, .literal_codes => { while (d.index < d.literal_trees) : (d.index += 1) { if (d.pc.stage == .idle) d.startPrefixCode(format.num_literal_symbols); d.literal_codes[d.index] = try d.readPrefixCode() orelse return .need_input; } d.index = 0; d.state = .command_codes; }, .command_codes => { while (d.index < d.categories[cat_command].types) : (d.index += 1) { if (d.pc.stage == .idle) d.startPrefixCode(format.num_command_symbols); d.command_codes[d.index] = try d.readPrefixCode() orelse return .need_input; } d.index = 0; d.state = .distance_codes; }, .distance_codes => { while (d.index < d.distance_trees) : (d.index += 1) { if (d.pc.stage == .idle) d.startPrefixCode(format.distanceAlphabetSize(d.npostfix, d.ndirect)); d.distance_codes[d.index] = try d.readPrefixCode() orelse return .need_input; } d.state = .command; }, .command => { const c = &d.categories[cat_command]; if (c.remaining == 0) { if (!d.switchBlock(cat_command)) return .need_input; } const sym = d.readSymbol(d.command_codes[c.current]) orelse return .need_input; c.remaining -= 1; d.command = format.command(sym); d.state = .command_extra; }, .command_extra => { const ins = format.insert_length_codes[d.command.insert_code]; const cpy = format.copy_length_codes[d.command.copy_code]; if (!br.has(@as(u32, ins.extra_bits) + cpy.extra_bits)) return .need_input; const insert_len = ins.base + br.read(ins.extra_bits).?; d.copy_length = cpy.base + br.read(cpy.extra_bits).?; if (insert_len > d.remaining) return error.MetaBlockOverrun; d.insert_remaining = insert_len; d.state = .literals; }, .literals => { if (try d.decodeLiterals()) |status| return status; // A meta-block may end after a command's literals; the copy // length then means nothing. d.state = if (d.remaining == 0) .mb_done else .distance; }, .distance => { var code: u16 = 0; if (d.command.implicit_distance) { d.distance = d.last_distances[0]; } else { const c = &d.categories[cat_distance]; if (c.remaining == 0) { if (!d.switchBlock(cat_distance)) return .need_input; } const ctx = format.distanceContext(d.copy_length); const tree = d.distance_codes[d.distance_map[@as(usize, c.current) * format.distance_contexts + ctx]]; code = try d.readDistanceCode(tree) orelse return .need_input; c.remaining -= 1; } const max_distance: u32 = @intCast(@min(d.pos, format.maxBackwardDistance(d.window_bits))); if (d.distance > max_distance) { try d.dictionaryWord(max_distance); d.state = .dictionary_copy; } else { if (code != 0) { // Through a copy: the literal is built in place, and // would otherwise read elements it has already // overwritten. const ld = d.last_distances; d.last_distances = .{ d.distance, ld[0], ld[1], ld[2] }; } if (d.copy_length > d.remaining) return error.MetaBlockOverrun; d.remaining -= d.copy_length; d.copy_remaining = d.copy_length; d.state = .copy; } }, .copy => { while (d.copy_remaining > 0) { const room = try d.makeRoom(); if (room == 0) return .need_output; const n: u32 = @intCast(@min(room, d.copy_remaining)); d.copyBack(d.distance, n); d.copy_remaining -= n; } d.state = if (d.remaining == 0) .mb_done else .command; }, .dictionary_copy => { while (d.word_pos < d.word_len) { const room = try d.makeRoom(); if (room == 0) return .need_output; const at = d.ringIndex(d.pos); const n = @min(room, d.word_len - d.word_pos, d.ring.len - at); @memcpy(d.ring[at..][0..n], d.word[d.word_pos..][0..n]); d.pos += n; d.word_pos += @intCast(n); } d.state = if (d.remaining == 0) .mb_done else .command; }, .mb_done => { d.state = if (d.is_last) .finish else .mb_last; }, .finish => { if (br.alignToByte() != 0) return error.InvalidPadding; d.state = .flush; }, .flush => { d.flushOut(); if (d.flushed < d.pos) return .need_output; d.state = .done; }, .done => return .done, }; } // The meta-block header. fn startHeader(d: *Decompressor) void { d.tables.clearRetainingCapacity(); d.category = 0; } fn nextCategory(d: *Decompressor) void { if (d.category == cat_distance) { d.state = .distance_params; } else { d.category += 1; d.state = .block_types; } } /// WBITS (RFC 7932 §9.1), or 0 for the reserved pattern. fn readWindowBits(br: *BitReader) ?u5 { if (!br.has(1)) return null; if (br.peek(1) == 0) { br.consume(1); return 16; } if (!br.has(4)) return null; const a = br.peek(4) >> 1; if (a != 0) { br.consume(4); return @intCast(17 + a); } if (!br.has(7)) return null; const b = br.peek(7) >> 4; br.consume(7); return switch (b) { 0 => 17, 1 => 0, else => @intCast(8 + b), }; } /// The variable-length code for 0..255 used by NBLTYPES and NTREES /// (RFC 7932 §9.2). fn readVarLenUint8(br: *BitReader) ?u16 { if (!br.has(1)) return null; if (br.peek(1) == 0) { br.consume(1); return 0; } if (!br.has(4)) return null; const n = br.peek(4) >> 1; if (n == 0) { br.consume(4); return 1; } if (!br.has(4 + n)) return null; const x = br.peek(4 + n) >> 4; br.consume(4 + n); return (@as(u16, 1) << @intCast(n)) + @as(u16, @intCast(x)); } // Prefix codes. fn startPrefixCode(d: *Decompressor, alphabet: u16) void { d.pc.stage = .kind; d.pc.alphabet = alphabet; d.pc.start = @intCast(d.tables.items.len); } /// Reads the prefix code `startPrefixCode` set up, returning where its table /// starts in `tables` once it is complete, or null if more input is needed. fn readPrefixCode(d: *Decompressor) Error!?u32 { const br = &d.br; const pc = &d.pc; while (true) switch (pc.stage) { .idle => unreachable, .kind => { const hskip = br.read(2) orelse return null; if (hskip == 1) { pc.stage = .simple_count; } else { pc.index = @intCast(hskip); pc.code_lengths = @splat(0); pc.space = 32; pc.num_codes = 0; pc.stage = .code_lengths; } }, .simple_count => { pc.nsym = @intCast((br.read(2) orelse return null) + 1); pc.index = 0; pc.stage = .simple_symbols; }, .simple_symbols => { const bits: u32 = std.math.log2_int(u16, pc.alphabet - 1) + 1; while (pc.index < pc.nsym) : (pc.index += 1) { // The tree-select bit follows the fourth symbol, and is read // with it so that the code is finished in one step. const n = if (pc.index == 3) bits + 1 else bits; if (!br.has(n)) return null; const sym: u16 = @intCast(br.peek(bits)); if (sym >= pc.alphabet) return error.InvalidPrefixCode; for (pc.symbols[0..pc.index]) |s| { if (s == sym) return error.InvalidPrefixCode; } br.consume(bits); pc.symbols[pc.index] = sym; } const lengths: []const u8 = switch (pc.nsym) { 1 => &.{1}, 2 => &.{ 1, 1 }, 3 => &.{ 1, 2, 2 }, 4 => if (br.read(1).? == 0) &.{ 2, 2, 2, 2 } else &.{ 1, 2, 3, 3 }, else => unreachable, }; @memset(pc.lengths[0..pc.alphabet], 0); for (pc.symbols[0..pc.nsym], lengths) |s, l| pc.lengths[s] = l; return try d.finishPrefixCode(); }, .code_lengths => { while (pc.index < format.num_code_length_symbols) { if (br.count < 4) br.refill(); const peeked = br.acc & 15; const len = format.code_length_code_bits[@intCast(peeked)]; if (len > br.count) return null; br.consume(len); const v = format.code_length_code_value[@intCast(peeked)]; pc.code_lengths[format.code_length_order[pc.index]] = v; pc.index += 1; if (v != 0) { pc.space -= @as(i32, 32) >> v; pc.num_codes += 1; if (pc.space <= 0) break; } } if (!(pc.num_codes == 1 or pc.space == 0)) return error.InvalidPrefixCode; try prefix_code.build(d.gpa, &d.tables, &pc.code_lengths); @memset(pc.lengths[0..pc.alphabet], 0); pc.symbol = 0; pc.prev_length = format.initial_repeated_code_length; pc.repeat = 0; pc.repeat_length = 0; pc.space = 32768; pc.stage = .symbols; }, .symbols => { const table = d.tables.items[pc.start..]; while (pc.symbol < pc.alphabet and pc.space > 0) { if (br.count < 8) br.refill(); const s = prefix_code.decode(table, br.acc, br.count) orelse return null; if (s.symbol < format.repeat_previous_code_length) { br.consume(s.length); const len: u8 = @intCast(s.symbol); pc.repeat = 0; pc.lengths[pc.symbol] = len; if (len != 0) { pc.prev_length = len; pc.space -= @as(i32, 32768) >> @intCast(len); } pc.symbol += 1; continue; } const extra_bits: u5 = if (s.symbol == format.repeat_previous_code_length) 2 else 3; if (s.length + extra_bits > br.count) return null; br.consume(s.length); const extra = br.read(extra_bits).?; const new_length = if (s.symbol == format.repeat_previous_code_length) pc.prev_length else 0; if (pc.repeat_length != new_length) { pc.repeat = 0; pc.repeat_length = new_length; } const old_repeat = pc.repeat; if (pc.repeat > 0) pc.repeat = (pc.repeat - 2) << extra_bits; pc.repeat += extra + 3; const delta = pc.repeat - old_repeat; if (pc.symbol + delta > pc.alphabet) return error.InvalidPrefixCode; @memset(pc.lengths[pc.symbol..][0..delta], pc.repeat_length); pc.symbol += @intCast(delta); if (pc.repeat_length != 0) { pc.space -= @as(i32, @intCast(delta)) * (@as(i32, 32768) >> @intCast(pc.repeat_length)); } } if (pc.space != 0) return error.InvalidPrefixCode; // The code length code's table is no longer wanted; the code's // own table goes where it was. d.tables.shrinkRetainingCapacity(pc.start); return try d.finishPrefixCode(); }, }; } fn finishPrefixCode(d: *Decompressor) Error!u32 { const pc = &d.pc; try prefix_code.build(d.gpa, &d.tables, pc.lengths[0..pc.alphabet]); pc.stage = .idle; return pc.start; } /// Decodes one symbol with the table starting at `table` in `tables`. inline fn readSymbol(d: *Decompressor, table: u32) ?u16 { const br = &d.br; if (br.count < format.max_code_length) br.refill(); const s = prefix_code.decode(d.tables.items[table..], br.acc, br.count) orelse return null; br.consume(s.length); return s.symbol; } // Context maps. /// Reads a context map (RFC 7932 §7.3) into `map`, returning false if more /// input is needed. fn readContextMap(d: *Decompressor, map: []u8, trees: u16) Error!bool { const br = &d.br; const cm = &d.cm; while (true) switch (cm.stage) { .rle => { if (!br.has(1)) return false; if (br.peek(1) == 0) { br.consume(1); cm.rle_max = 0; } else { if (!br.has(5)) return false; cm.rle_max = @intCast((br.peek(5) >> 1) + 1); br.consume(5); } d.startPrefixCode(trees + cm.rle_max); cm.stage = .code; }, .code => { cm.code = try d.readPrefixCode() orelse return false; cm.index = 0; cm.stage = .values; }, .values => { const table = d.tables.items[cm.code..]; while (cm.index < map.len) { if (br.count < format.max_code_length + format.max_context_map_rle) br.refill(); const s = prefix_code.decode(table, br.acc, br.count) orelse return false; if (s.symbol == 0) { br.consume(s.length); map[cm.index] = 0; cm.index += 1; } else if (s.symbol <= cm.rle_max) { const extra_bits: u32 = s.symbol; if (s.length + extra_bits > br.count) return false; br.consume(s.length); const zeros = (@as(u32, 1) << @intCast(extra_bits)) + br.read(extra_bits).?; if (cm.index + zeros > map.len) return error.InvalidContextMap; @memset(map[cm.index..][0..zeros], 0); cm.index += zeros; } else { br.consume(s.length); map[cm.index] = @intCast(s.symbol - cm.rle_max); cm.index += 1; } } cm.stage = .imtf; }, .imtf => { const imtf = br.read(1) orelse return false; if (imtf == 1) inverseMoveToFront(map); // The map's own prefix code is not needed again. d.tables.shrinkRetainingCapacity(cm.code); return true; }, }; } fn inverseMoveToFront(v: []u8) void { var mtf: [256]u8 = undefined; for (&mtf, 0..) |*m, i| m.* = @intCast(i); for (v) |*x| { const index = x.*; const value = mtf[index]; x.* = value; std.mem.copyBackwards(u8, mtf[1 .. @as(usize, index) + 1], mtf[0..index]); mtf[0] = value; } } // Block switches. /// A block count: a symbol and its extra bits, read together. fn readBlockLength(d: *Decompressor, table: u32) ?u32 { const br = &d.br; if (br.count < format.max_code_length + 24) br.refill(); const s = prefix_code.decode(d.tables.items[table..], br.acc, br.count) orelse return null; const code = format.block_length_codes[s.symbol]; if (s.length + @as(u32, code.extra_bits) > br.count) return null; br.consume(s.length); return code.base + br.read(code.extra_bits).?; } /// Reads a block switch command for category `c` (RFC 7932 §6), returning /// false if more input is needed. fn switchBlock(d: *Decompressor, c: usize) bool { const cat = &d.categories[c]; // A category with a single block type reads no type or count code, and // its count is set so that it outlasts any meta-block (see // `format.unbounded_block_length`), so a switch is never attempted here // with one type. Reaching this with `types == 1` is the invalid state // behind CVE-2026-111497: `type_code` and `count_code` would be read from // tables that were never built, and `current` could land outside the // per-type code arrays. Assert it rather than trust it. std.debug.assert(cat.types >= 2); if (!d.switch_pending) { const sym = d.readSymbol(cat.type_code) orelse return false; const next: u16 = switch (sym) { 0 => cat.previous, 1 => if (cat.current + 1 == cat.types) 0 else cat.current + 1, else => sym - 2, }; cat.previous = cat.current; cat.current = next; d.switch_pending = true; } cat.remaining = d.readBlockLength(cat.count_code) orelse return false; d.switch_pending = false; return true; } // Commands. /// Decodes the current command's literals, returning a status if it has to /// stop before they are all done. fn decodeLiterals(d: *Decompressor) Error!?Status { const c = &d.categories[cat_literal]; while (d.insert_remaining > 0) { const room = try d.makeRoom(); if (room == 0) return .need_output; var n = @min(room, d.insert_remaining); while (n > 0) : (n -= 1) { if (c.remaining == 0) { if (!d.switchBlock(cat_literal)) return .need_input; } const p1 = d.previousByte(1); const p2 = d.previousByte(2); const ctx = context.id(d.context_modes[c.current], p1, p2); const tree = d.literal_codes[d.literal_map[@as(usize, c.current) * format.literal_contexts + ctx]]; const sym = d.readSymbol(tree) orelse return .need_input; c.remaining -= 1; d.put(@intCast(sym)); d.insert_remaining -= 1; d.remaining -= 1; } } return null; } /// Reads a distance code and its extra bits with the table at `table`, /// setting `distance`, and returns the code. fn readDistanceCode(d: *Decompressor, table: u32) Error!?u16 { const br = &d.br; if (br.count < format.max_code_length + format.max_distance_bits) br.refill(); const s = prefix_code.decode(d.tables.items[table..], br.acc, br.count) orelse return null; const code = s.symbol; if (code < format.num_distance_short_codes) { br.consume(s.length); const ld = d.last_distances; const resolved: i64 = switch (code) { 0...3 => ld[code], 4...9 => @as(i64, ld[0]) + shortCodeDelta(code - 4), else => @as(i64, ld[1]) + shortCodeDelta(code - 10), }; if (resolved <= 0) return error.InvalidDistance; d.distance = @intCast(resolved); return code; } const direct_end = format.num_distance_short_codes + @as(u16, d.ndirect); if (code < direct_end) { br.consume(s.length); d.distance = code - 15; return code; } const x: u32 = code - direct_end; const ndistbits: u32 = 1 + (x >> (@as(u5, d.npostfix) + 1)); if (s.length + ndistbits > br.count) return null; br.consume(s.length); const dextra = br.read(ndistbits).?; const hcode = x >> d.npostfix; const lcode = x & ((@as(u32, 1) << d.npostfix) - 1); const offset = ((2 + (hcode & 1)) << @intCast(ndistbits)) - 4; d.distance = ((offset + dextra) << d.npostfix) + lcode + d.ndirect + 1; return code; } /// The adjustment special distance codes 4..9 and 10..15 make: -1, +1, -2, /// +2, -3, +3. fn shortCodeDelta(i: u16) i64 { const magnitude: i64 = @intCast(i / 2 + 1); return if (i % 2 == 0) -magnitude else magnitude; } /// Sets up a static dictionary reference for the current command, whose /// distance reaches `max_distance` or further back (RFC 7932 §8). fn dictionaryWord(d: *Decompressor, max_distance: u32) Error!void { const len = d.copy_length; if (len < dictionary.min_word_length or len > dictionary.max_word_length) return error.InvalidDictionaryReference; const word_id = d.distance - max_distance - 1; const bits = dictionary.size_bits_by_length[len]; const index = word_id & ((@as(u32, 1) << bits) - 1); const id = word_id >> bits; if (id >= transform.transforms.len) return error.InvalidDictionaryReference; const n = transform.apply(transform.transforms[id], dictionary.word(len, index), &d.word); if (n > d.remaining) return error.MetaBlockOverrun; d.remaining -= @intCast(n); d.word_len = @intCast(n); d.word_pos = 0; } // The window. inline fn ringIndex(d: *const Decompressor, p: u64) usize { return @as(usize, @truncate(p)) & (d.ring.len - 1); } /// The byte `back` positions before the next one, or zero before the start /// of the stream. inline fn previousByte(d: *const Decompressor, back: u64) u8 { return if (d.pos < back) 0 else d.ring[d.ringIndex(d.pos - back)]; } /// Appends one byte. There must be room for it. inline fn put(d: *Decompressor, b: u8) void { d.ring[d.ringIndex(d.pos)] = b; d.pos += 1; } /// How many bytes can be appended to the window before something has to /// give, making room by growing the window or by handing output to the /// caller. Zero means the caller's buffer is full. fn makeRoom(d: *Decompressor) Allocator.Error!usize { const window = @as(usize, 1) << d.window_bits; if (d.ring.len < window and d.pos == d.ring.len) { // Until the window reaches full size it never wraps: everything // produced so far may yet be referred to. const new_len = if (d.ring.len == 0) @min(window, initial_window) else d.ring.len * 2; d.ring = try d.gpa.realloc(d.ring, new_len); } if (d.ring.len < window) return d.ring.len - @as(usize, @intCast(d.pos)); var free = d.ring.len - @as(usize, @intCast(d.pos - d.flushed)); if (free == 0) { d.flushOut(); free = d.ring.len - @as(usize, @intCast(d.pos - d.flushed)); } return free; } /// The window a stream starts with, grown by doubling. const initial_window = 1 << 16; /// Appends `n` bytes copied from `dist` bytes back, which may overlap what /// is being written: a distance of 1 repeats the last byte `n` times. There /// must be room for all of them. fn copyBack(d: *Decompressor, dist: u32, n: u32) void { var left: usize = n; while (left > 0) { const dst = d.ringIndex(d.pos); const src = d.ringIndex(d.pos - dist); const chunk = @min(left, d.ring.len - dst, d.ring.len - src); if (src + chunk <= dst or dst + chunk <= src) { @memcpy(d.ring[dst..][0..chunk], d.ring[src..][0..chunk]); } else { // Overlapping: byte by byte, front to back, so that a short // distance repeats what it has just written. for (0..chunk) |i| d.ring[dst + i] = d.ring[src + i]; } d.pos += chunk; left -= chunk; } } /// Hands as much decoded output to the caller as its buffer has room for. fn flushOut(d: *Decompressor) void { while (d.flushed < d.pos and d.out_pos < d.out.len) { const at = d.ringIndex(d.flushed); const n = @min(@as(usize, @intCast(d.pos - d.flushed)), d.ring.len - at, d.out.len - d.out_pos); @memcpy(d.out[d.out_pos..][0..n], d.ring[at..][0..n]); d.out_pos += n; d.flushed += n; } } test "window bits" { const cases = [_]struct { bits: []const u8, expect: ?u5 }{ .{ .bits = &.{0b0}, .expect = 16 }, .{ .bits = &.{0b0011}, .expect = 18 }, .{ .bits = &.{0b1111}, .expect = 24 }, .{ .bits = &.{0b0000001}, .expect = 17 }, .{ .bits = &.{0b0100001}, .expect = 10 }, .{ .bits = &.{0b1110001}, .expect = 15 }, .{ .bits = &.{0b0010001}, .expect = 0 }, }; for (cases) |case| { var br: BitReader = .{}; br.begin(case.bits); try std.testing.expectEqual(case.expect, readWindowBits(&br)); } } test "variable-length uint8" { const cases = [_]struct { bits: u16, expect: u16 }{ .{ .bits = 0b0, .expect = 0 }, .{ .bits = 0b0001, .expect = 1 }, .{ .bits = 0b10011, .expect = 3 }, .{ .bits = 0b0110111, .expect = 11 }, .{ .bits = 0b111_1111_1111, .expect = 255 }, }; for (cases) |case| { var br: BitReader = .{}; const bytes = std.mem.toBytes(std.mem.nativeToLittle(u16, case.bits)); br.begin(&bytes); try std.testing.expectEqual(case.expect, readVarLenUint8(&br)); } } test "inverse move-to-front" { var v = [_]u8{ 1, 0, 2, 2, 0 }; inverseMoveToFront(&v); try std.testing.expectEqualSlices(u8, &.{ 1, 1, 2, 0, 0 }, &v); } test "short code deltas" { for ([_]i64{ -1, 1, -2, 2, -3, 3 }, 0..) |want, i| { try std.testing.expectEqual(want, shortCodeDelta(@intCast(i))); } }