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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Block splitting (RFC 7932 §6): dividing one of a meta-block's three//! streams of symbols — literals, insert-and-copy commands, or distances —//! into blocks, each coded with the prefix code of its block type, so that//! a stream whose statistics change part way through is not stuck with one//! code for all of it.//!//! The stream is cut into equal chunks whose histograms are clustered into//! a few types. Then, a few times over, every symbol is assigned to the type//! that codes it best allowing for the cost of a switch, and the types'//! histograms are rebuilt from what they were given.
const std = @import("std");const Allocator = std.mem.Allocator;
const format = @import("format.zig");const histogram = @import("histogram.zig");
/// A run of symbols coded with one block type.pub const Block = struct { type: u8, len: u32 };
pub const Options = struct { /// The fewest symbols a chunk holds when the types are first guessed. chunk: usize, /// The most block types. max_types: usize, /// What a switch from one block type to another costs, in bits. switch_cost: f64, /// How many times to reassign symbols and rebuild the histograms. iterations: usize = 3,};
/// Splits `symbols` into blocks, appended to `blocks`, returning how many/// types they use. The first block is type 0. A stream not worth splitting/// is one block of type 0.pub fn split(gpa: Allocator, symbols: []const u16, alphabet: usize, options: Options, blocks: *std.ArrayList(Block)) Allocator.Error!usize { blocks.clearRetainingCapacity(); if (symbols.len == 0) return 1; const one: Block = .{ .type = 0, .len = @intCast(symbols.len) }; // At most 64 chunks to start with, so that clustering them stays cheap. const chunk = @max(options.chunk, (symbols.len + 63) / 64); const chunks = (symbols.len + chunk - 1) / chunk; if (chunks < 2 or options.max_types < 2) { try blocks.append(gpa, one); return 1; }
var hists = try gpa.alloc(u32, @max(chunks, options.max_types) * alphabet); defer gpa.free(hists); @memset(hists, 0); for (symbols, 0..) |s, i| hists[(i / chunk) * alphabet + s] += 1; const assignment = try gpa.alloc(u16, chunks); defer gpa.free(assignment); var k = try histogram.cluster(gpa, hists[0 .. chunks * alphabet], alphabet, assignment, options.max_types); if (k < 2) { try blocks.append(gpa, one); return 1; }
const ids = try gpa.alloc(u8, symbols.len); defer gpa.free(ids); const renumber = try gpa.alloc(u8, k); defer gpa.free(renumber); for (0..options.iterations) |_| { try histogram.findBlocks(gpa, symbols, alphabet, hists[0 .. k * alphabet], k, options.switch_cost, ids); // Types nothing chose fall away, and the rest are numbered in order // of first use, which puts type 0 first as the format requires. @memset(renumber, 0xff); var used: usize = 0; for (ids) |*id| { if (renumber[id.*] == 0xff) { renumber[id.*] = @intCast(used); used += 1; } id.* = renumber[id.*]; } k = used; @memset(hists[0 .. k * alphabet], 0); for (symbols, ids) |s, id| hists[@as(usize, id) * alphabet + s] += 1; if (k < 2) break; } if (k < 2) { try blocks.append(gpa, one); return 1; }
var start: usize = 0; for (1..ids.len + 1) |i| { if (i == ids.len or ids[i] != ids[start]) { try blocks.append(gpa, .{ .type = ids[start], .len = @intCast(i - start) }); start = i; } } return k;}
test "a stream that changes halfway splits there" { const gpa = std.testing.allocator; var blocks: std.ArrayList(Block) = .empty; defer blocks.deinit(gpa); var prng: std.Random.DefaultPrng = .init(5); var symbols: [20000]u16 = undefined; for (&symbols, 0..) |*s, i| { s.* = if (i < 12000) prng.random().intRangeAtMost(u16, 0, 15) else prng.random().intRangeAtMost(u16, 100, 140); } const k = try split(gpa, &symbols, 256, .{ .chunk = 512, .max_types = 8, .switch_cost = 28 }, &blocks); try std.testing.expectEqual(2, k); try std.testing.expectEqual(2, blocks.items.len); try std.testing.expectEqual(Block{ .type = 0, .len = 12000 }, blocks.items[0]);
// One kind of noise throughout: no reason to split. for (&symbols) |*s| s.* = prng.random().int(u8); try std.testing.expectEqual(1, try split(gpa, &symbols, 256, .{ .chunk = 512, .max_types = 8, .switch_cost = 28 }, &blocks)); try std.testing.expectEqual(1, blocks.items.len);}