// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Writing the elements of the format: the stream header, meta-block //! headers, and prefix codes. Each is the counterpart of something the //! decompressor reads, and is tested by having the decompressor read it. const std = @import("std"); const Allocator = std.mem.Allocator; const BitWriter = @import("BitWriter.zig"); const format = @import("format.zig"); const prefix_code = @import("prefix_code.zig"); const Error = Allocator.Error; /// WBITS (RFC 7932 §9.1). pub fn windowBits(bw: *BitWriter, gpa: Allocator, window_bits: u5) Error!void { std.debug.assert(window_bits >= format.min_window_bits and window_bits <= format.max_window_bits); switch (window_bits) { 16 => try bw.writeBits(gpa, 1, 0), 17 => try bw.writeBits(gpa, 7, 1), 18...24 => try bw.writeBits(gpa, 4, (@as(u64, window_bits - 17) << 1) | 1), else => try bw.writeBits(gpa, 7, (@as(u64, window_bits - 8) << 4) | 1), } } /// The variable-length code for 0..255 (RFC 7932 §9.2). pub fn varLenUint8(bw: *BitWriter, gpa: Allocator, value: u8) Error!void { if (value == 0) return bw.writeBits(gpa, 1, 0); const n: u6 = std.math.log2_int(u8, value); try bw.writeBits(gpa, 1, 1); try bw.writeBits(gpa, 3, n); try bw.writeBits(gpa, n, value - (@as(u64, 1) << n)); } /// ISLAST = 0, then MNIBBLES and MLEN - 1 for a meta-block of `length` /// bytes, written with as few nibbles as it takes. pub fn metaBlockLength(bw: *BitWriter, gpa: Allocator, length: u32) Error!void { std.debug.assert(length >= 1 and length <= 1 << 24); const v = length - 1; const nibbles: u6 = if (v < 1 << 16) 4 else if (v < 1 << 20) 5 else 6; try bw.writeBits(gpa, 1, 0); try bw.writeBits(gpa, 2, nibbles - 4); try bw.writeBits(gpa, nibbles * 4, v); } /// A meta-block holding `data` as it is. pub fn uncompressedMetaBlock(bw: *BitWriter, gpa: Allocator, data: []const u8) Error!void { try metaBlockLength(bw, gpa, @intCast(data.len)); try bw.writeBits(gpa, 1, 1); try bw.alignToByte(gpa); try bw.writeBytes(gpa, data); } /// How many bits `uncompressedMetaBlock` would write for `length` bytes, /// starting `start_bit` bits into a byte. pub fn uncompressedMetaBlockBits(length: u32, start_bit: u6) u64 { const v = length - 1; const nibbles: u64 = if (v < 1 << 16) 4 else if (v < 1 << 20) 5 else 6; const header = start_bit + 1 + 2 + nibbles * 4 + 1; return std.mem.alignForward(u64, header, 8) - start_bit + @as(u64, length) * 8; } /// An empty metadata meta-block, which carries the stream to a byte /// boundary: what a flush ends with. pub fn emptyMetadata(bw: *BitWriter, gpa: Allocator) Error!void { // ISLAST = 0, MNIBBLES = 0 (written 11), reserved 0, MSKIPBYTES = 0. try bw.writeBits(gpa, 6, 0b00_0_11_0); try bw.alignToByte(gpa); } /// ISLAST = 1, ISLASTEMPTY = 1, and the padding to the end of the byte: the /// end of the stream. pub fn lastEmpty(bw: *BitWriter, gpa: Allocator) Error!void { try bw.writeBits(gpa, 2, 0b11); try bw.alignToByte(gpa); } /// A prefix code ready to write symbols with: for each symbol its length /// and its code with the bits reversed, as the stream carries them. pub const Code = struct { lengths: [format.num_command_symbols]u8, codes: [format.num_command_symbols]u16, alphabet: u16, /// The symbols that occur, in order, if there are four or fewer. used: [4]u16, num_used: u16, /// Chooses the code for an alphabet whose symbols occur `counts` times. /// An alphabet where nothing occurs still gets a code, of one symbol, /// because the format requires one. pub fn init(code: *Code, counts: []const u32, limit: u4) void { code.alphabet = @intCast(counts.len); const n = prefix_code.lengthsFromCounts(counts, limit, &code.lengths); code.num_used = @intCast(n); var k: usize = 0; for (counts, 0..) |c, sym| { if (c == 0 or k == code.used.len) continue; code.used[k] = @intCast(sym); k += 1; } if (n == 0) { code.num_used = 1; code.used[0] = 0; } if (n < 2) { @memset(code.codes[0..counts.len], 0); return; } prefix_code.assignCodes(code.lengths[0..counts.len], &code.codes); for (code.lengths[0..counts.len], code.codes[0..counts.len]) |l, *c| { if (l != 0) c.* = @bitReverse(c.*) >> @intCast(16 - @as(u5, @intCast(l))); } } pub inline fn write(code: *const Code, bw: *BitWriter, gpa: Allocator, symbol: u16) Error!void { try bw.writeBits(gpa, @intCast(code.lengths[symbol]), code.codes[symbol]); } /// How many bits writing `counts` occurrences takes. pub fn cost(code: *const Code, counts: []const u32) u64 { var bits: u64 = 0; for (counts, code.lengths[0..counts.len]) |c, l| bits += @as(u64, c) * l; return bits; } }; /// Writes the description of `code` (RFC 7932 §3.4, §3.5): a simple prefix /// code if four or fewer symbols occur, otherwise a complex one. pub fn prefixCode(bw: *BitWriter, gpa: Allocator, code: *const Code) Error!void { if (code.num_used <= 4) return simplePrefixCode(bw, gpa, code); return complexPrefixCode(bw, gpa, code); } fn simplePrefixCode(bw: *BitWriter, gpa: Allocator, code: *const Code) Error!void { const n = code.num_used; // The lengths a simple code gives its symbols depend only on the order // they are listed in, so list them shortest code first. var symbols = code.used; const Ctx = struct { code: *const Code, fn lessThan(ctx: @This(), a: u16, b: u16) bool { const la = ctx.code.lengths[a]; const lb = ctx.code.lengths[b]; return la < lb or (la == lb and a < b); } }; std.mem.sortUnstable(u16, symbols[0..n], Ctx{ .code = code }, Ctx.lessThan); const bits: u6 = std.math.log2_int(u16, code.alphabet - 1) + 1; try bw.writeBits(gpa, 2, 1); try bw.writeBits(gpa, 2, n - 1); for (symbols[0..n]) |s| try bw.writeBits(gpa, bits, s); // Four symbols: lengths 2, 2, 2, 2 or 1, 2, 3, 3. if (n == 4) try bw.writeBits(gpa, 1, @intFromBool(code.lengths[symbols[0]] == 1)); } /// The fixed code a complex prefix code's code length code lengths are /// written with (RFC 7932 §3.5): bit count and bits, indexed by length. const code_length_code_bits = [6]u6{ 2, 4, 3, 2, 2, 4 }; const code_length_code_codes = [6]u64{ 0, 7, 3, 2, 1, 15 }; fn complexPrefixCode(bw: *BitWriter, gpa: Allocator, code: *const Code) Error!void { // The code lengths, run-length coded with symbols 16 and 17, as the // reference implementation does it. var length = code.alphabet; while (length > 0 and code.lengths[length - 1] == 0) length -= 1; var rle: [format.num_command_symbols]u8 = undefined; var extra: [format.num_command_symbols]u8 = undefined; var n: usize = 0; var previous: u8 = format.initial_repeated_code_length; var i: usize = 0; while (i < length) { const value = code.lengths[i]; var reps: usize = 1; while (i + reps < length and code.lengths[i + reps] == value) reps += 1; if (value == 0) { repeatZeros(reps, &rle, &extra, &n); } else { repeatValue(previous, value, reps, &rle, &extra, &n); previous = value; } i += reps; } var counts: [format.num_code_length_symbols]u32 = @splat(0); for (rle[0..n]) |s| counts[s] += 1; var cl: Code = undefined; cl.init(&counts, 5); // A single code length symbol is coded with no bits, but its length in // the code length code must still be written as non-zero. var cl_lengths: [format.num_code_length_symbols]u8 = undefined; @memcpy(&cl_lengths, cl.lengths[0..format.num_code_length_symbols]); if (cl.num_used == 1) cl_lengths[cl.used[0]] = 1; var to_store: usize = format.num_code_length_symbols; if (cl.num_used > 1) { while (to_store > 0 and cl_lengths[format.code_length_order[to_store - 1]] == 0) to_store -= 1; } var skip: usize = 0; if (cl_lengths[format.code_length_order[0]] == 0 and cl_lengths[format.code_length_order[1]] == 0) { skip = 2; if (cl_lengths[format.code_length_order[2]] == 0) skip = 3; } try bw.writeBits(gpa, 2, skip); for (format.code_length_order[skip..to_store]) |sym| { const l = cl_lengths[sym]; try bw.writeBits(gpa, code_length_code_bits[l], code_length_code_codes[l]); } for (rle[0..n], extra[0..n]) |s, e| { try cl.write(bw, gpa, s); switch (s) { format.repeat_previous_code_length => try bw.writeBits(gpa, 2, e), format.repeat_zero_code_length => try bw.writeBits(gpa, 3, e), else => {}, } } } /// The longest run of zeros a context map's run-length code is allowed to /// describe with one symbol is `(2 << max) - 1`; the reference compressor /// caps `max` at 6. const max_context_map_rle = 6; /// Writes a context map (RFC 7932 §7.3) whose values run from 0 to /// `trees - 1`, the way the reference compressor does: through a /// move-to-front transform, so that a value repeated runs to zeros, and /// then with runs of zeros coded by length. pub fn contextMap(bw: *BitWriter, gpa: Allocator, map: []const u8, trees: u16) Error!void { std.debug.assert(trees >= 2); var values: [format.literal_contexts * format.max_block_types]u16 = undefined; std.debug.assert(map.len <= values.len); // Move to front, the inverse of the decompressor's transform. var mtf: [256]u8 = undefined; for (&mtf, 0..) |*m, i| m.* = @intCast(i); for (map, values[0..map.len]) |v, *out| { const index = std.mem.findScalar(u8, &mtf, v).?; out.* = @intCast(index); std.mem.copyBackwards(u8, mtf[1 .. index + 1], mtf[0..index]); mtf[0] = v; } // The longest run of zeros decides how many run-length symbols there // are. var longest: usize = 0; { var i: usize = 0; while (i < map.len) { var run: usize = 0; while (i < map.len and values[i] == 0) : (i += 1) run += 1; longest = @max(longest, run); while (i < map.len and values[i] != 0) i += 1; } } const rle_max: u16 = if (longest == 0) 0 else @min(std.math.log2_int(usize, longest), max_context_map_rle); // Symbols, each with its extra bits: a run of 2^k + extra zeros is // symbol k, a value v is symbol v + rle_max. var symbols: [format.literal_contexts * format.max_block_types]u16 = undefined; var extras: [format.literal_contexts * format.max_block_types]u16 = undefined; var n: usize = 0; var i: usize = 0; while (i < map.len) { if (values[i] != 0) { symbols[n] = values[i] + rle_max; extras[n] = 0; n += 1; i += 1; continue; } var reps: usize = 0; while (i < map.len and values[i] == 0) : (i += 1) reps += 1; while (reps > 0) { if (reps < @as(usize, 2) << @intCast(rle_max)) { const k = std.math.log2_int(usize, reps); symbols[n] = k; extras[n] = @intCast(reps - (@as(usize, 1) << k)); n += 1; break; } symbols[n] = rle_max; extras[n] = @intCast((@as(usize, 1) << @intCast(rle_max)) - 1); n += 1; reps -= (@as(usize, 2) << @intCast(rle_max)) - 1; } } var counts: [format.max_block_types + max_context_map_rle]u32 = @splat(0); const alphabet = trees + rle_max; for (symbols[0..n]) |sym| counts[sym] += 1; var code: Code = undefined; code.init(counts[0..alphabet], format.max_code_length); if (rle_max == 0) { try bw.writeBits(gpa, 1, 0); } else { try bw.writeBits(gpa, 1, 1); try bw.writeBits(gpa, 4, rle_max - 1); } try prefixCode(bw, gpa, &code); for (symbols[0..n], extras[0..n]) |sym, extra| { try code.write(bw, gpa, sym); if (sym > 0 and sym <= rle_max) try bw.writeBits(gpa, @intCast(sym), extra); } // IMTF: undo the move to front. try bw.writeBits(gpa, 1, 1); } fn repeatValue(previous: u8, value: u8, count: usize, rle: []u8, extra: []u8, n: *usize) void { var reps = count; if (previous != value) { push(rle, extra, n, value, 0); reps -= 1; } if (reps == 7) { push(rle, extra, n, value, 0); reps -= 1; } if (reps < 3) { for (0..reps) |_| push(rle, extra, n, value, 0); return; } // Each further 16 multiplies the count so far by four, so the extra // bits are the base-4 digits of the count, most significant first. const start = n.*; reps -= 3; while (true) { push(rle, extra, n, format.repeat_previous_code_length, @intCast(reps & 3)); reps >>= 2; if (reps == 0) break; reps -= 1; } std.mem.reverse(u8, rle[start..n.*]); std.mem.reverse(u8, extra[start..n.*]); } fn repeatZeros(count: usize, rle: []u8, extra: []u8, n: *usize) void { var reps = count; if (reps == 11) { push(rle, extra, n, 0, 0); reps -= 1; } if (reps < 3) { for (0..reps) |_| push(rle, extra, n, 0, 0); return; } const start = n.*; reps -= 3; while (true) { push(rle, extra, n, format.repeat_zero_code_length, @intCast(reps & 7)); reps >>= 3; if (reps == 0) break; reps -= 1; } std.mem.reverse(u8, rle[start..n.*]); std.mem.reverse(u8, extra[start..n.*]); } fn push(rle: []u8, extra: []u8, n: *usize, symbol: u8, e: u8) void { rle[n.*] = symbol; extra[n.*] = e; n.* += 1; } test "the fixed code for code length code lengths matches the decoder's" { for (code_length_code_bits, code_length_code_codes, 0..) |bits, c, len| { try std.testing.expectEqual(bits, format.code_length_code_bits[c]); try std.testing.expectEqual(len, format.code_length_code_value[c]); } }