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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Choosing the context mode for a meta-block's literals (RFC 7932 §7).//!//! Each literal falls in one of 64 contexts decided by the two bytes before//! it, under one of four context modes. Coding each context with its own//! prefix code would describe the literals best, but every code costs bits//! to write down, so contexts with similar statistics share one, and the//! context map says which code each context uses.//!//! `plan` ranks the four modes by the entropy of their contexts, which is//! cheap, then clusters the contexts of the best one to see whether context//! modeling is worth having at all. The encoder works out the final codes//! itself, by block type as well as context.
const std = @import("std");const Allocator = std.mem.Allocator;
const context = @import("context.zig");const format = @import("format.zig");const histogram = @import("histogram.zig");
const num_contexts = format.literal_contexts;const alphabet = format.num_literal_symbols;
/// Working space, 64 KiB, kept between meta-blocks: a literal histogram for/// each context.pub const Scratch = struct { counts: [num_contexts * alphabet]u32,};
pub const Plan = struct { mode: context.Mode, /// How many literal codes the contexts cluster into; 1 means context /// modeling does not pay. trees: u16, /// For each context, its code. The codes' histograms are at the front /// of `Scratch.counts`. map: [num_contexts]u8,};
/// A stretch of literals: where they start in the data, and how many.pub const Run = struct { start: u32, len: u32 };
/// Decides how to code the literals in `runs`, which are positions in/// `data`; `base` is the position in the stream of `data[0]`, which says/// where the stream starts and the bytes before a literal are zero.pub fn plan(gpa: Allocator, scratch: *Scratch, data: []const u8, base: u64, runs: []const Run, max_trees: u16) Allocator.Error!Plan { // One code for everything, the alternative to beat. var single: [alphabet]u32 = @splat(0); for (runs) |r| { for (data[r.start..][0..r.len]) |b| single[b] += 1; } const single_cost = histogram.cost(&single);
// The mode whose contexts tell the literals apart best. var best_mode: context.Mode = .utf8; var best_entropy = std.math.inf(f64); for ([_]context.Mode{ .utf8, .signed, .lsb6, .msb6 }) |mode| { count(scratch, data, base, runs, mode); var e: f64 = 0; for (0..num_contexts) |ctx| e += histogram.entropy(scratch.counts[ctx * alphabet ..][0..alphabet]); if (e < best_entropy) { best_entropy = e; best_mode = mode; } }
count(scratch, data, base, runs, best_mode); var assignment: [num_contexts]u16 = undefined; const trees = try histogram.cluster(gpa, &scratch.counts, alphabet, &assignment, max_trees); var map: [num_contexts]u8 = undefined; var previous_tree: u8 = 0; for (assignment, &map) |a, *m| { if (a != histogram.unassigned) previous_tree = @intCast(a); m.* = previous_tree; } var clustered: f64 = 40 + 8 * @as(f64, @floatFromInt(trees)); for (0..trees) |t| clustered += histogram.cost(scratch.counts[t * alphabet ..][0..alphabet]); if (trees < 2 or clustered >= single_cost) return .{ .mode = .lsb6, .trees = 1, .map = @splat(0) }; return .{ .mode = best_mode, .trees = @intCast(trees), .map = map };}
fn count(scratch: *Scratch, data: []const u8, base: u64, runs: []const Run, mode: context.Mode) void { @memset(&scratch.counts, 0); for (runs) |r| { for (r.start..r.start + r.len) |k| { const p1 = previous(data, base, k, 1); const p2 = previous(data, base, k, 2); scratch.counts[@as(usize, context.id(mode, p1, p2)) * alphabet + data[k]] += 1; } }}
fn previous(data: []const u8, base: u64, k: usize, back: usize) u8 { return if (base + k < back) 0 else data[k - back];}
test "plan finds the contexts that matter" { const gpa = std.testing.allocator; const scratch = try gpa.create(Scratch); defer gpa.destroy(scratch);
// Letters always follow digits and digits always follow letters: two // regimes that the UTF-8 mode's classes tell apart. var data: [8192]u8 = undefined; var prng: std.Random.DefaultPrng = .init(3); for (&data, 0..) |*b, i| { b.* = if (i % 2 == 0) prng.random().intRangeAtMost(u8, 'a', 'z') else prng.random().intRangeAtMost(u8, '0', '9'); } const runs = [_]Run{.{ .start = 0, .len = data.len }}; const p = try plan(gpa, scratch, &data, 0, &runs, 16); try std.testing.expect(p.trees >= 2); // Each code has only the symbols of its regime. for (0..p.trees) |t| { const h = scratch.counts[t * alphabet ..][0..alphabet]; var letters = false; var digits = false; for (h, 0..) |c, sym| { if (c == 0) continue; if (std.ascii.isAlphabetic(@intCast(sym))) letters = true; if (std.ascii.isDigit(@intCast(sym))) digits = true; } try std.testing.expect(!(letters and digits)); }
// Noise has no context to exploit. prng.random().bytes(&data); try std.testing.expectEqual(1, (try plan(gpa, scratch, &data, 0, &runs, 16)).trees);}