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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163#!/usr/bin/env python3# SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us># SPDX-License-Identifier: MIT
"""Makes the test vectors in tests/data with the reference compressor.
Every input is generated here from a fixed seed, so nothing of anyone else'sis checked in and the whole set can be made again exactly:
nix develop -c python3 tools/make_vectors.py
Each input is compressed at a spread of qualities, window sizes and modes,which between them make the compressor use everything a decompressor has tohandle: uncompressed and compressed meta-blocks, every context mode, blockswitching, the static dictionary and its transforms, and windows small enoughto wrap many times over.
Only the compressed streams are kept. tests/vectors.zig records the lengthand SHA-256 of what each must decompress to, and each is checked here againstthe reference decoder before it is written."""
import hashlibimport mathimport osimport randomimport struct
import brotli
HERE = os.path.dirname(os.path.abspath(__file__))ROOT = os.path.dirname(HERE)DATA = os.path.join(ROOT, "tests", "data")
def dictionary_words(): """The ASCII words of the static dictionary, which is what makes word salad compress through dictionary references.""" data = open(os.path.join(ROOT, "src", "dictionary.bin"), "rb").read() ndbits = [0, 0, 0, 0, 10, 10, 11, 11, 10, 10, 10, 10, 10, 9, 9, 8, 7, 7, 8, 7, 7, 6, 6, 5, 5] words, offset = [], 0 for length, bits in enumerate(ndbits): if length < 4: continue for i in range(1 << bits): w = data[offset + i * length : offset + (i + 1) * length] if all(97 <= c <= 122 for c in w): words.append(w) offset += length << bits return words
def text(size, seed): """Sentences of dictionary words, with capitals, punctuation and the odd HTML tag, which is the kind of input the dictionary's transforms were made for.""" rng = random.Random(seed) words = dictionary_words() common = words[:300] out = bytearray() while len(out) < size: n = rng.randint(4, 16) sentence = [] for i in range(n): w = rng.choice(common if rng.random() < 0.7 else words) if i == 0 or rng.random() < 0.05: w = w[:1].upper() + w[1:] if rng.random() < 0.02: w = w.upper() sentence.append(w) s = b" ".join(sentence) + rng.choice([b". ", b", ", b"! ", b"? ", b".\n", b"\n\n"]) if rng.random() < 0.05: s = b'<a href="' + rng.choice(words) + b'.html">' + s + b"</a>" out += s return bytes(out[:size])
def noise(size, seed): return random.Random(seed).randbytes(size)
def samples(size, seed): """Little-endian 16-bit samples of a noisy chord: what the signed context mode is for.""" rng = random.Random(seed) out = bytearray() for i in range(size // 2): v = 8000 * math.sin(i / 20) + 3000 * math.sin(i / 7.3) + rng.gauss(0, 200) out += struct.pack("<h", max(-32768, min(32767, int(v)))) return bytes(out)
def spread_copies(seed): """Random blocks repeated almost a full 16 MiB window later, so that a decoder with the largest window has to reach back nearly all the way, and keep doing so after its window has wrapped.""" block = noise(64 << 10, seed) gap = bytes((16 << 20) - (192 << 10)) return block + gap + block + gap[: 1 << 20] + block
MODES = {"generic": brotli.MODE_GENERIC, "text": brotli.MODE_TEXT, "font": brotli.MODE_FONT}
# (name, input, quality, lgwin, mode)def vectors(): t = text(80 << 10, 1) v = [] for q in range(12): v.append(("text-q%d" % q, t, q, 22, "generic")) for lgwin in (10, 16, 24): for q in (5, 11): v.append(("text-q%d-w%d" % (q, lgwin), t, q, lgwin, "generic")) v.append(("text-q11-mode-text", t, 11, 22, "text")) v.append(("text-q11-mode-font", t, 11, 22, "font")) v.append(("text-short-q11", t[:200], 11, 22, "generic")) n = noise(24 << 10, 2) for q in (0, 5, 11): v.append(("noise-q%d" % q, n, q, 22, "generic")) s = samples(48 << 10, 3) for q in (2, 9, 11): v.append(("samples-q%d" % q, s, q, 22, "generic")) z = bytes(1 << 20) v.append(("zeros-q0", z, 0, 22, "generic")) v.append(("zeros-q11-w10", z, 11, 10, "generic")) mixed = text(40 << 10, 4) + noise(8 << 10, 5) + samples(24 << 10, 6) + text(24 << 10, 7) for q in (4, 11): v.append(("mixed-q%d" % q, mixed, q, 18, "generic")) v.append(("byte-q11", b"x", 11, 22, "generic")) v.append(("empty-q11", b"", 11, 22, "generic")) v.append(("far-copies-q5-w24", spread_copies(8), 5, 24, "generic")) return v
def main(): os.makedirs(DATA, exist_ok=True) for f in os.listdir(DATA): if f.endswith(".br"): os.remove(os.path.join(DATA, f)) rows = [] for name, data, q, lgwin, mode in vectors(): c = brotli.compress(data, quality=q, lgwin=lgwin, mode=MODES[mode]) assert brotli.decompress(c) == data, name open(os.path.join(DATA, name + ".br"), "wb").write(c) rows.append((name, len(data), hashlib.sha256(data).hexdigest())) print("%-24s %9d -> %8d" % (name, len(data), len(c))) with open(os.path.join(ROOT, "tests", "vectors.zig"), "w") as f: # REUSE-IgnoreStart f.write("// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>\n") f.write("// SPDX-License-Identifier: MIT\n\n") # REUSE-IgnoreEnd f.write("//! Streams made by the reference compressor, with the length and SHA-256 of\n") f.write("//! what each decompresses to. Generated by tools/make_vectors.py; do not\n") f.write("//! edit.\n\n") f.write("pub const Vector = struct { name: []const u8, compressed: []const u8, length: usize, sha256: []const u8 };\n\n") f.write("pub const vectors = [_]Vector{\n") for name, length, digest in rows: f.write(' .{ .name = "%s", .compressed = @embedFile("data/%s.br"), .length = %d, .sha256 = "%s" },\n' % (name, name, length, digest)) f.write("};\n")
if __name__ == "__main__": main()