ws-arch: codecs/Brotli (RFC 7932 decoder: all meta-block kinds, context modes/maps, static dictionary + 121 transforms, large windows) and archive/br (single-stream archive); tools/brotli_static.py generates codecs/Brotli/Static from the brotli sources (MIT, licenses/brotli-LICENSE.txt); fixtures via python brotli + CLI

This commit is contained in:
4DBug committed 2026-10-31 08:36:16 -05:00
1 parent 0ca32501a4
commit 0bfd70e1ca
12 files changed
+2524

No files matched your search

+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env python3
# Brotli static data generator (python3 -I tools/brotli_static.py [brotli-source-dir]): writes
# src/Formats/codecs/Brotli/Static.luau from the official brotli C sources (MIT; licenses/brotli-LICENSE.txt):
# the 122784-byte RFC 7932 static dictionary (c/common/dictionary_inc.h, stored deflated + base64), the context
# lookup table (c/common/context.c) and the 121 word transforms (c/common/transform.c).
# Without an argument the source comes from `nix build nixpkgs#brotli.src`.
import base64, os, re, subprocess, sys, zlib
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
OUT = os.path.join(ROOT, "src", "Formats", "codecs", "Brotli", "Static.luau")
def c_array(text, name):
m = re.search(re.escape(name) + r"[^=]*=\s*\{(.*?)\};", text, re.S)
body = re.sub(r"/\*.*?\*/", "", m.group(1), flags=re.S)
body = body.replace("BROTLI_TRANSFORM_IDENTITY", "0").replace("BROTLI_TRANSFORM_UPPERCASE_FIRST", "10")
body = body.replace("BROTLI_TRANSFORM_UPPERCASE_ALL", "11")
body = re.sub(r"BROTLI_TRANSFORM_OMIT_LAST_(\d)", lambda k: k.group(1), body)
body = re.sub(r"BROTLI_TRANSFORM_OMIT_FIRST_(\d)", lambda k: str(11 + int(k.group(1))), body)
return [int(x, 0) for x in re.findall(r"0x[0-9a-fA-F]+|\d+", body)]
def c_string(text, name):
m = re.search(re.escape(name) + r"[^=]*=\s*(.*?);", text, re.S)
parts = re.findall(r'"((?:[^"\\]|\\.)*)"', re.sub(r"/\*.*?\*/", "", m.group(1), flags=re.S))
s = "".join(parts)
return s.encode("latin-1").decode("unicode_escape").encode("latin-1") + b"\0"
def b64_chunks(data, width=96):
s = base64.b64encode(data).decode()
return [s[i:i + width] for i in range(0, len(s), width)]
def main():
src = sys.argv[1] if len(sys.argv) > 1 else subprocess.run(
["nix", "build", "nixpkgs#brotli.src", "--no-link", "--print-out-paths"], capture_output=True, check=True,
text=True).stdout.strip()
common = os.path.join(src, "c", "common")
dict_text = open(os.path.join(common, "dictionary_inc.h")).read()
dictionary = bytes(c_array(dict_text, "kBrotliDictionaryData"))
assert len(dictionary) == 122784
ctx = bytes(c_array(open(os.path.join(common, "context.c")).read(), "_kBrotliContextLookupTable"))
assert len(ctx) == 2048
tr_text = open(os.path.join(common, "transform.c")).read()
ps = c_string(tr_text, "kPrefixSuffix")
assert len(ps) == 217, len(ps)
psmap = c_array(tr_text, "kPrefixSuffixMap")
trans = c_array(tr_text, "kTransformsData")
assert len(psmap) == 50 and len(trans) == 363
z = zlib.compress(dictionary, 9)
lines = [
"--!strict",
"-- codecs/Brotli/Static: GENERATED by tools/brotli_static.py from the brotli C sources (MIT, Google; see",
"-- licenses/brotli-LICENSE.txt) - do not edit. The RFC 7932 static dictionary (122784 bytes, deflated, base64),",
"-- the context lookup table (Appendix B, 4 modes x 512) and the 121 word transforms (Appendix B).",
"return {",
"\tdictionarySize = %d," % len(dictionary),
"\tdictionaryCrc = %d," % zlib.crc32(dictionary),
"\tdictionary = {",
]
lines += ['\t\t"%s",' % c for c in b64_chunks(z)]
lines += ["\t},", "\tcontext = {"]
lines += ['\t\t"%s",' % c for c in b64_chunks(ctx)]
lines += ["\t},"]
lines += ['\tprefixSuffix = "%s",' % base64.b64encode(ps).decode()]
lines += ["\tprefixSuffixMap = { %s }," % ", ".join(map(str, psmap))]
lines += ["\ttransforms = {"]
for i in range(0, len(trans), 30):
lines.append("\t\t%s," % ", ".join(map(str, trans[i:i + 30])))
lines += ["\t},", "}", ""]
with open(OUT, "w") as f:
f.write("\n".join(lines))
print("brotli_static: wrote %s (%d bytes)" % (os.path.relpath(OUT, ROOT), os.path.getsize(OUT)))
if __name__ == "__main__":
main()
+101
View File
@@ -0,0 +1,101 @@
# Brotli fixtures (tools/fixtures.py): deterministic corpora compressed by the reference encoder (python brotli
# through nix, and the brotli CLI for the large-window extension): every quality 0..11, windows 10..24, the text /
# font / generic modes, empty input, dictionary-heavy English, and a few-MB bench corpus.
# tests/gen/brotli.luau { corpora = { [name] = bytes }, cases = { { name, corpus, data } } }
# tests/gen/brotli_bench.luau { size, crc, data }
import os, pickle, random, zlib
ENCODE = r'''
import brotli, pickle, sys
jobs = pickle.load(sys.stdin.buffer)
out = []
for data, q, w, mode in jobs:
m = {"generic": brotli.MODE_GENERIC, "text": brotli.MODE_TEXT, "font": brotli.MODE_FONT}[mode]
out.append(brotli.compress(data, mode=m, quality=q, lgwin=w))
sys.stdout.buffer.write(pickle.dumps(out))
'''
WORDS = ("the of and to in is that for it as was with be by on not he this are or his from at which but have an they "
"you were her she there one all we their been has who more will would if so can its what when about into than "
"them only other time new some could these two may first then do any like my now over such our man me even "
"most made after also did many before must through back years where much your way well down should because "
"each just those people Mr how too little state good very make world still own see men work long get here "
"between both life being under never day same another know while last might us great old year off come since "
"against go came right used take three himself few house use during without again place American around "
"however home small found Mrs thought went say part once general high upon school every don't does got united "
"left number course war until always away something fact though water less public put think almost hand "
"enough far took head yet government system better set told nothing night end why called didn't eyes find "
"going look asked later knew point next program city business give group toward young days let room president "
"side social present given several order national possible rather second face per among form important often "
"things looked early white case John become large big need four within felt along children saw best church "
"ever least power development light thing seemed family interest want members mind country area others done "
"turned although open God service certain kind problem began different door thus help sense means whole "
"matter perhaps itself York it's times law human line above name example action company local show whether "
"five history gave today either act feet across taken past quite anything seen having death week experience "
"really body word half field").split()
def english(rng, n):
out = []
size = 0
while size < n:
k = rng.randint(4, 16)
s = " ".join(rng.choice(WORDS) for _ in range(k))
s = s[0].upper() + s[1:] + rng.choice([". ", ", ", "; ", "! ", "? ", ".\n", ". The ", " - "])
if rng.random() < 0.05:
s = '<a href="http://www.' + rng.choice(WORDS) + '.com/">' + s + "</a>\n"
out.append(s)
size += len(s)
return "".join(out).encode()[:n]
def text_corpus(limit):
base = os.path.dirname(os.__file__)
out = bytearray()
for name in sorted(os.listdir(base)):
if name.endswith(".py"):
with open(os.path.join(base, name), "rb") as f:
out += f.read()
if len(out) >= limit:
break
return bytes(out[:limit])
def generate(ctx):
rng = random.Random(7)
text = text_corpus(400000)
corpora = {
"empty": b"",
"one": b"a",
"english": english(rng, 120000),
"text": text[:150000],
"random": rng.randbytes(30000),
"runs": b"abc" * 4000 + b"\0" * 20000 + bytes(range(256)) * 40 + b"z" * 300,
"binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(30000)),
"utf8": ("Grüße, Привет, 你好, こんにちは, ¡Hola! " * 600).encode(),
"far": (lambda r: r + rng.randbytes(70000) + r)(rng.randbytes(9000)),
}
jobs, names = [], []
for cname, data in corpora.items():
for q in range(12):
jobs.append((data, q, 22, "generic"))
names.append(("%s/q%d" % (cname, q), cname))
for w in (10, 12, 16, 18, 24):
jobs.append((data, 9, w, "generic"))
names.append(("%s/q9-w%d" % (cname, w), cname))
for mode in ("text", "font"):
for q in (5, 11):
jobs.append((data, q, 20, mode))
names.append(("%s/%s-q%d" % (cname, mode, q), cname))
outs = pickle.loads(ctx.python(["brotli"], ENCODE, input=pickle.dumps(jobs)))
cases = [{"name": n, "corpus": c, "data": d} for (n, c), d in zip(names, outs)]
# the large-window extension (brotli CLI), on the far-match corpus and the text
for cname in ("far", "text", "english"):
for q in (5, 11):
d = ctx.nix("brotli", ["brotli", "-c", "-q", str(q), "--large_window=26"], input=corpora[cname])
cases.append({"name": "%s/large-q%d" % (cname, q), "corpus": cname, "data": d})
ctx.emit("brotli", {"corpora": corpora, "cases": cases})
bench = (text + english(rng, 1500000) + corpora["binary"] * 10 + text) * 2
bench = bench[:4000000]
bout = pickle.loads(ctx.python(["brotli"], ENCODE, input=pickle.dumps([(bench, 9, 22, "generic")])))[0]
ctx.emit("brotli_bench", {"size": len(bench), "crc": zlib.crc32(bench), "data": bout})