vec: merge ws/arch (codecs/Raster for SVG)

This commit is contained in:
4DBug committed 2026-10-31 08:54:57 -05:00
commit 027210c4e1
66 files changed
+15049 -1

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()
+102
View File
@@ -0,0 +1,102 @@
# 7z fixtures (tools/fixtures.py): a small tree (text, x86 machine code, runs, an empty file, empty and nested
# directories, UTF-16 names with accents and a surrogate pair) archived by 7-Zip 2x (nix _7zz) with many method chains:
# LZMA / LZMA2 / copy / Deflate, solid and non-solid, BCJ / ARM64 / delta filters, plain and compressed headers; plus
# archives whose methods are not supported (BZip2, PPMd, BCJ2, AES) and an empty archive.
# tests/gen/7z.luau { files = { { name, dir, data?, mtime } }, cases = { { name, data, unsupported? } } }
import os, random, subprocess, sys, tempfile
TOOL = "_7zz"
def tree(rng):
with open(os.path.realpath(sys.executable), "rb") as f:
code = f.read(60000)
base = os.path.dirname(os.__file__)
text = b""
for name in sorted(os.listdir(base)):
if name.endswith(".py"):
with open(os.path.join(base, name), "rb") as f:
text += f.read()
if len(text) > 50000:
break
return [
("readme.txt", text[:50000]),
("bin/code.bin", code),
("bin/runs.dat", b"ab" * 5000 + b"\0" * 9000 + bytes(range(256)) * 8),
("bin/random.dat", rng.randbytes(3000)),
("empty.txt", b""),
("emptydir/", None),
("a/b/c/deep.txt", b"deep\n" * 10),
("héllo wörld ☃.txt", "unicode ☃\n".encode()),
("\U0001d11e clef.txt", b"g clef\n"),
]
def generate(ctx):
rng = random.Random(77)
files = tree(rng)
mtime = 1600000000
out_files = []
cases = []
with tempfile.TemporaryDirectory() as d:
src = os.path.join(d, "src")
for name, data in files:
p = os.path.join(src, name)
if data is None:
os.makedirs(p, exist_ok=True)
os.utime(p, (mtime, mtime))
out_files.append({"name": name.rstrip("/"), "dir": True, "mtime": mtime})
else:
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "wb") as f:
f.write(data)
os.utime(p, (mtime + 60, mtime + 60))
out_files.append({"name": name, "dir": False, "data": data, "mtime": mtime + 60})
for sub in ("bin", "a", "a/b", "a/b/c"):
os.utime(os.path.join(src, sub), (mtime, mtime))
out_files.append({"name": sub, "dir": True, "mtime": mtime})
def make(name, args, unsupported=None):
arc = os.path.join(d, name + ".7z")
if os.path.exists(arc):
os.remove(arc)
subprocess.run(["nix", "shell", "nixpkgs#" + TOOL, "-c", "7zz", "a", "-bd", "-y", arc] + args + ["."],
cwd=src, capture_output=True, check=True)
with open(arc, "rb") as f:
c = {"name": name, "data": f.read()}
if unsupported:
c["unsupported"] = unsupported
cases.append(c)
make("lzma-nonsolid", ["-m0=LZMA", "-ms=off", "-mhc=off"])
make("lzma-solid", ["-m0=LZMA:d=1m", "-ms=on"])
make("lzma2-solid", ["-m0=LZMA2", "-ms=on"])
make("lzma2-mt-blocks", ["-m0=LZMA2:d=64k:c=20k", "-ms=on", "-mmt=4"])
make("lzma2-hc-off", ["-m0=LZMA2", "-mhc=off"])
make("copy", ["-m0=Copy", "-mhc=off"])
make("copy-hc", ["-m0=Copy"])
make("deflate", ["-m0=Deflate", "-ms=on"])
make("bcj-lzma", ["-m0=BCJ", "-m1=LZMA", "-ms=on"])
make("bcj-lzma2", ["-m0=BCJ", "-m1=LZMA2", "-ms=off"])
make("arm64-lzma2", ["-m0=ARM64", "-m1=LZMA2"])
make("arm-lzma2", ["-m0=ARM", "-m1=LZMA2"])
make("delta-lzma", ["-m0=Delta:4", "-m1=LZMA"])
make("ppc-sparc", ["-m0=PPC", "-m1=SPARC", "-m2=LZMA2"])
make("lzma-lc-lp", ["-m0=LZMA:lc=0:lp=2:pb=0", "-ms=e"])
make("auto", ["-mx=9"])
make("fast", ["-mx=1"])
make("bzip2", ["-m0=BZip2", "-mhc=off"], unsupported="bzip2")
make("ppmd", ["-m0=PPMd", "-mhc=off"], unsupported="ppmd")
make("bcj2", ["-m0=BCJ2", "-m1=LZMA", "-m2=LZMA", "-m3=LZMA", "-mb0s0:1", "-mb0s1:2", "-mb0s2:3", "-mhc=off"],
unsupported="bcj2")
make("aes", ["-m0=LZMA2", "-mhc=off", "-pSecret"], unsupported="aes")
# an empty archive
arc = os.path.join(d, "empty.7z")
empty = os.path.join(d, "emptysrc")
os.makedirs(empty)
subprocess.run(["nix", "shell", "nixpkgs#" + TOOL, "-c", "7zz", "a", "-bd", "-y", arc, "-x!*", "."],
cwd=empty, capture_output=True)
if os.path.exists(arc):
with open(arc, "rb") as f:
cases.append({"name": "empty", "data": f.read(), "empty": True})
ctx.emit("7z", {"files": out_files, "cases": cases})
+181
View File
@@ -0,0 +1,181 @@
# Font reference data (run by tools/fixtures/fonts.py inside a nix python with fonttools, freetype-py, uharfbuzz and
# brotli). Reads a JSON list of {name, path | b64} on stdin; writes JSON on stdout: per font the bytes, the metrics,
# names, cmap samples (fontTools), advances / side bearings / control boxes / areas of sample glyphs (fontTools pens),
# kerning of sample pairs (HarfBuzz GPOS 'kern', or FreeType for 'kern' tables), FreeType renders (no hinting) of
# sample glyphs at a few sizes, and the WOFF / WOFF2 versions (fontTools).
import base64, io, json, sys
import freetype
import uharfbuzz as hb
from fontTools.pens.areaPen import AreaPen
from fontTools.pens.boundsPen import ControlBoundsPen
from fontTools.ttLib import TTFont, newTable
from fontTools.ttLib.tables._k_e_r_n import KernTable_format_0
SAMPLE_TEXT = "AVTWYLPFoaey.,'\"-0147"
SIZES = [11, 24, 47]
def b64(b):
return base64.b64encode(b).decode()
def load(spec):
if "path" in spec:
return open(spec["path"], "rb").read()
return base64.b64decode(spec["b64"])
def with_kern_table(data):
"""a copy with a 'kern' format 0 table of a few pairs (none of the sample fonts has one)"""
f = TTFont(io.BytesIO(data))
cmap = f.getBestCmap()
order = f.getGlyphOrder()
pairs = {}
letters = "AVTWYLoaey"
for i, a in enumerate(letters):
for j, b in enumerate(letters):
if ord(a) in cmap and ord(b) in cmap and (i * 7 + j * 3) % 4 == 0:
pairs[(cmap[ord(a)], cmap[ord(b)])] = -((i * 13 + j * 5) % 90) - 10
k = newTable("kern")
k.version = 0
st = KernTable_format_0()
st.version, st.coverage, st.format = 0, 1, 0
st.kernTable = pairs
k.kernTables = [st]
f["kern"] = k
if "GPOS" in f:
del f["GPOS"]
out = io.BytesIO()
f.save(out)
return out.getvalue()
def collection(datas):
from fontTools.ttLib.ttCollection import TTCollection
c = TTCollection()
c.fonts = [TTFont(io.BytesIO(d)) for d in datas]
out = io.BytesIO()
c.save(out)
return out.getvalue()
def reference(name, data, index=0):
f = TTFont(io.BytesIO(data), fontNumber=index)
gs = f.getGlyphSet()
order = f.getGlyphOrder()
head, hhea, maxp = f["head"], f["hhea"], f["maxp"]
names = f["name"]
def nm(i):
r = names.getName(i, 3, 1, 0x409) or names.getName(i, 3, 1) or names.getName(i, 1, 0, 0) or names.getName(i, 0, 3)
return r.toUnicode() if r else ""
cmap = f.getBestCmap() or {}
cps = sorted(cmap)
sample_cps = cps[:: max(1, len(cps) // 150)] + [0x10FFFF, 0xFFFF, 0x7F, 0x9999]
cm = [[cp, f.getGlyphID(cmap[cp]) if cp in cmap else 0] for cp in sample_cps]
# glyphs: every glyph for small fonts, else a sample (plus the sample text's)
gids = list(range(len(order))) if len(order) <= 400 else list(range(0, len(order), len(order) // 300))
for ch in SAMPLE_TEXT:
if ord(ch) in cmap:
gids.append(f.getGlyphID(cmap[ord(ch)]))
gids = sorted(set(gids))
hmtx = f["hmtx"]
glyphs = []
for g in gids:
gn = order[g]
adv, lsb = hmtx[gn]
bp = ControlBoundsPen(gs)
gs[gn].draw(bp)
ap = AreaPen(gs)
gs[gn].draw(ap)
e = {"gid": g, "adv": adv, "lsb": lsb, "area": float(ap.value)}
if bp.bounds:
e["box"] = [float(v) for v in bp.bounds]
glyphs.append(e)
# kerning
kern = []
letters = [c for c in SAMPLE_TEXT if ord(c) in cmap]
if "kern" in f and "GPOS" not in f:
face = freetype.Face(io.BytesIO(data), index)
for a in letters:
for b in letters:
ga, gb = f.getGlyphID(cmap[ord(a)]), f.getGlyphID(cmap[ord(b)])
v = face.get_kerning(a, b, freetype.FT_KERNING_UNSCALED) # freetype-py maps characters to glyphs
kern.append([ga, gb, v.x])
elif "GPOS" in f:
blob = hb.Blob(data)
hface = hb.Face(blob, index)
hfont = hb.Font(hface)
feats = {"kern": True, "liga": False, "clig": False, "calt": False, "mark": False, "mkmk": False, "ccmp": False, "locl": False, "rlig": False, "dist": False, "curs": False}
for a in letters:
for b in letters:
buf = hb.Buffer()
buf.add_str(a + b)
buf.guess_segment_properties()
hb.shape(hfont, buf, feats)
ga, gb = buf.glyph_infos[0].codepoint, buf.glyph_infos[1].codepoint
adv = buf.glyph_positions[0].x_advance - hmtx[order[ga]][0]
kern.append([ga, gb, adv])
# FreeType renders
face = freetype.Face(io.BytesIO(data), index)
renders = []
rg = [f.getGlyphID(cmap[ord(c)]) for c in "AgQ@&e%" if ord(c) in cmap]
for px in SIZES:
face.set_pixel_sizes(0, px)
for g in rg:
face.load_glyph(g, freetype.FT_LOAD_NO_HINTING | freetype.FT_LOAD_NO_BITMAP)
face.glyph.render(freetype.FT_RENDER_MODE_NORMAL)
bm = face.glyph.bitmap
rows = []
for y in range(bm.rows):
rows.append(bytes(bm.buffer[y * bm.pitch: y * bm.pitch + bm.width]))
renders.append({"gid": g, "px": px, "w": bm.width, "h": bm.rows, "left": face.glyph.bitmap_left,
"top": face.glyph.bitmap_top, "pixels": b64(b"".join(rows))})
os2 = f["OS/2"] if "OS/2" in f else None
return {
"name": name, "data": b64(data), "index": index, "upem": head.unitsPerEm, "ascent": hhea.ascent,
"descent": hhea.descent, "lineGap": hhea.lineGap, "numGlyphs": maxp.numGlyphs, "family": nm(16) or nm(1),
"style": nm(17) or nm(2), "fullName": nm(4), "weight": os2.usWeightClass if os2 else 0,
"cff": "CFF " in f, "cmap": cm, "glyphs": glyphs, "kern": kern, "renders": renders,
}
def flavors(data):
out = {}
for fl in ("woff", "woff2"):
f = TTFont(io.BytesIO(data))
f.flavor = fl
b = io.BytesIO()
f.save(b)
out[fl] = b64(b.getvalue())
from fontTools.ttLib import woff2
src, dst = io.BytesIO(data), io.BytesIO()
woff2.compress(src, dst, transform_tables={"glyf", "loca", "hmtx"})
out["woff2h"] = b64(dst.getvalue())
return out
def main():
specs = json.load(sys.stdin)
fonts = {}
for s in specs:
fonts[s["name"]] = load(s)
res = {"fonts": [], "woff": []}
for name, data in fonts.items():
res["fonts"].append(reference(name, data))
kd = with_kern_table(fonts["ProggyClean"] if "ProggyClean" in fonts else next(iter(fonts.values())))
res["fonts"].append(reference("kern-table", kd))
names = [n for n in ("Karla-Regular", "Cousine-Regular") if n in fonts]
if len(names) == 2:
ttc = collection([fonts[n] for n in names])
r = reference("collection-1", ttc, 1)
res["fonts"].append(r)
res["ttc"] = {"data": b64(ttc), "count": 2, "second": names[1]}
# woff / woff2 of every font (the reference values are the sfnt's own)
for name, data in fonts.items():
fl = flavors(data)
res["woff"].append({"name": name, "woff": fl["woff"], "woff2": fl["woff2"], "woff2h": fl["woff2h"]})
json.dump(res, sys.stdout)
main()
+105
View File
@@ -0,0 +1,105 @@
# BMFont fixtures (tools/fixtures.py): a bitmap font rendered from Karla-Regular (imgui-luau fonts, or DejaVu Sans
# from nixpkgs when missing) with FreeType + Pillow, written by an independent Python writer of the three AngelCode
# encodings (text, XML, binary v3) from the BMFont documentation, plus its page PNG.
# tests/gen/bmfont.luau { text, xml, binary, page (png bytes), desc = { info, common, pages, chars, kernings },
# crops = { { id, crc } } (CRC-32 of each glyph's alpha crop) }
import base64, json, os, subprocess
FONT = os.path.join(os.environ.get("IMGUI_FONTS", os.path.expanduser("~/dev/luau/imgui/imgui-luau/fonts")), "Karla-Regular.ttf")
CODE = r'''
import base64, io, json, struct, sys, zlib
import freetype
from PIL import Image
data = base64.b64decode(sys.stdin.read())
face = freetype.Face(io.BytesIO(data))
face.set_pixel_sizes(0, 24)
chars = [c for c in range(32, 127)] + [0xE9, 0x2014]
page = Image.new("RGBA", (256, 256), (255, 255, 255, 0))
x, y, rowh = 1, 1, 0
out = []
crops = []
for cp in chars:
face.load_char(chr(cp), freetype.FT_LOAD_RENDER | freetype.FT_LOAD_NO_HINTING)
g = face.glyph
bm = g.bitmap
w, h = bm.width, bm.rows
if x + w + 1 > 256:
x, y, rowh = 1, y + rowh + 1, 0
alpha = bytes(bm.buffer[r * bm.pitch + c] for r in range(h) for c in range(w))
for r in range(h):
for c in range(w):
page.putpixel((x + c, y + r), (255, 255, 255, alpha[r * w + c]))
out.append({"id": cp, "x": x, "y": y, "width": w, "height": h, "xoffset": g.bitmap_left,
"yoffset": 19 - g.bitmap_top, "xadvance": g.advance.x // 64, "page": 0, "chnl": 15})
crops.append({"id": cp, "crc": zlib.crc32(alpha)})
x += w + 1
rowh = max(rowh, h)
kern = []
for a in "AVTWYLo":
for b in "AVTWYoe.":
k = face.get_kerning(a, b).x // 64
kern.append([ord(a), ord(b), -((ord(a) * 7 + ord(b)) % 5) - 1])
info = {"face": "Karla \"Test\" & Co", "size": 24, "bold": 0, "italic": 1, "charset": "", "unicode": 1, "stretchH": 100,
"smooth": 1, "aa": 1, "padding": [1, 2, 3, 4], "spacing": [1, 1], "outline": 0}
common = {"lineHeight": 28, "base": 19, "scaleW": 256, "scaleH": 256, "pages": 1, "packed": 0, "alphaChnl": 0,
"redChnl": 4, "greenChnl": 4, "blueChnl": 4}
pages = ["karla_0.png"]
CHAR_KEYS = ["id", "x", "y", "width", "height", "xoffset", "yoffset", "xadvance", "page", "chnl"]
def tq(s): return '"' + s.replace('"', "") + '"'
lines = ["info face=%s size=24 bold=0 italic=1 charset=\"\" unicode=1 stretchH=100 smooth=1 aa=1 padding=1,2,3,4 spacing=1,1 outline=0" % tq(info["face"]),
"common lineHeight=28 base=19 scaleW=256 scaleH=256 pages=1 packed=0 alphaChnl=0 redChnl=4 greenChnl=4 blueChnl=4",
'page id=0 file="karla_0.png"', "chars count=%d" % len(out)]
for c in out:
lines.append("char " + " ".join("%s=%d" % (k, c[k]) for k in CHAR_KEYS))
lines.append("kernings count=%d" % len(kern))
for k in kern:
lines.append("kerning first=%d second=%d amount=%d" % tuple(k))
text = "\r\n".join(lines) + "\r\n"
def xe(s): return s.replace("&", "&amp;").replace("<", "&lt;").replace('"', "&quot;")
xl = ['<?xml version="1.0"?>', "<font>",
' <info face="%s" size="24" bold="0" italic="1" charset="" unicode="1" stretchH="100" smooth="1" aa="1" padding="1,2,3,4" spacing="1,1" outline="0"/>' % xe(info["face"]),
' <common lineHeight="28" base="19" scaleW="256" scaleH="256" pages="1" packed="0" alphaChnl="0" redChnl="4" greenChnl="4" blueChnl="4"/>',
" <pages>", ' <page id="0" file="karla_0.png" />', " </pages>", ' <chars count="%d">' % len(out)]
for c in out:
xl.append(" <char " + " ".join('%s="%d"' % (k, c[k]) for k in CHAR_KEYS) + " />")
xl.append(" </chars>")
xl.append(' <kernings count="%d">' % len(kern))
for k in kern:
xl.append(' <kerning first="%d" second="%d" amount="%d" />' % tuple(k))
xl += [" </kernings>", "</font>"]
xml = "\n".join(xl) + "\n"
face_name = info["face"].encode()
b = bytearray(b"BMF\x03")
blk = struct.pack("<hBBHBBBBBBBB", 24, 0x80 | 0x40 | 0x20, 0, 100, 1, 1, 2, 3, 4, 1, 1, 0) + face_name + b"\0"
b += struct.pack("<BI", 1, len(blk)) + blk
blk = struct.pack("<HHHHHBBBBB", 28, 19, 256, 256, 1, 0, 0, 4, 4, 4)
b += struct.pack("<BI", 2, len(blk)) + blk
blk = b"karla_0.png\0"
b += struct.pack("<BI", 3, len(blk)) + blk
blk = b"".join(struct.pack("<IHHHHhhhBB", *[c[k] for k in CHAR_KEYS]) for c in out)
b += struct.pack("<BI", 4, len(blk)) + blk
blk = b"".join(struct.pack("<IIh", *k) for k in kern)
b += struct.pack("<BI", 5, len(blk)) + blk
png = io.BytesIO()
page.save(png, "PNG")
json.dump({"text": base64.b64encode(text.encode()).decode(), "xml": base64.b64encode(xml.encode()).decode(),
"binary": base64.b64encode(bytes(b)).decode(), "page": base64.b64encode(png.getvalue()).decode(),
"desc": {"info": info, "common": common, "pages": pages, "chars": out, "kernings": kern}, "crops": crops},
sys.stdout)
'''
def generate(ctx):
path = FONT
if not os.path.exists(path):
out = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#dejavu_fonts"], capture_output=True,
check=True, text=True).stdout.strip().split("\n")[-1]
path = os.path.join(out, "share", "fonts", "truetype", "DejaVuSans.ttf")
raw = ctx.python(["freetype-py", "pillow"], CODE, input=base64.b64encode(open(path, "rb").read()))
res = json.loads(raw)
d = base64.b64decode
for k in ("text", "xml", "binary", "page"):
res[k] = d(res[k])
res["ttf"] = open(path, "rb").read()
ctx.emit("bmfont", res)
+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})
+61
View File
@@ -0,0 +1,61 @@
# Bzip2 fixtures (tools/fixtures.py): deterministic corpora compressed with Python's bz2 module (libbzip2) at block
# sizes 1..9, RLE1 edge cases (runs of 1..300 bytes, runs straddling block ends), every byte value, random data,
# concatenated streams with trailing garbage; plus a 4 MB bench corpus.
# tests/gen/bzip2.luau { corpora = { [name] = bytes }, cases = { { name, corpus, data } } }
# tests/gen/bzip2_bench.luau { size, crc, data }
import bz2, os, zlib
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 = ctx.rng(7)
runs = bytearray()
for n in list(range(1, 20)) + [250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 300, 1000, 5000]:
runs += bytes([n % 251]) * n + b"x"
corpora = {
"empty": b"",
"one": b"a",
"two": b"ab",
"four": b"aaaa",
"five": b"aaaaa",
"text": text_corpus(300000),
"random": rng.randbytes(60000),
"runs": bytes(runs),
"zeros": b"\0" * 250000,
"allbytes": bytes(range(256)) * 50,
"binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(40000)),
# a run crossing the 100k block boundary at level 1
"boundary": b"q" * 99990 + b"r" * 30 + rng.randbytes(1000),
# more than 18 Huffman group switches / many symbols in use
"skewed": bytes(rng.choice(range(256)) if rng.random() < 0.1 else 65 for _ in range(120000)),
}
cases = []
for cname, data in corpora.items():
for level in (1, 5, 9) if len(data) > 1000 else (9,):
cases.append(("%s/l%d" % (cname, level), cname, bz2.compress(data, level)))
for level in range(1, 10):
cases.append(("text/all-l%d" % level, "text", bz2.compress(corpora["text"], level)))
corpora["multi"] = corpora["text"][:20000] + b"" + corpora["runs"]
multi = bz2.compress(corpora["text"][:20000], 9) + bz2.compress(b"", 1) + bz2.compress(corpora["runs"], 3)
cases.append(("multi/streams", "multi", multi))
cases.append(("multi/trailing", "multi", multi + b"garbage after the last stream"))
ctx.emit("bzip2", {
"corpora": corpora,
"cases": [{"name": n, "corpus": c, "data": d} for n, c, d in cases],
})
bench = bytearray()
while len(bench) < 4_000_000:
bench += corpora["text"] + corpora["binary"] + rng.randbytes(20000)
bench = bytes(bench[:4_000_000])
ctx.emit("bzip2_bench", {"size": len(bench), "crc": zlib.crc32(bench), "data": bz2.compress(bench, 9)})
+37
View File
@@ -0,0 +1,37 @@
# Font fixtures (tools/fixtures.py): the imgui-luau fonts (TrueType: Cousine, DroidSans, Karla, Proggy*, Roboto, read
# from ~/dev/luau/imgui/imgui-luau/fonts or $IMGUI_FONTS; skipped if missing) and Source Sans 3 (CFF OpenType, nixpkgs
# source-sans), plus a copy of ProggyClean with a 'kern' table and a two-font collection, both made with fontTools.
# Reference values come from tools/fixtures/_font_reference.py: fontTools (metrics, names, cmap, hmtx, control boxes,
# areas, WOFF / WOFF2), HarfBuzz (GPOS kerning), FreeType (kern tables, unhinted renders).
# tests/gen/fonts.luau { fonts = { { name, data, upem, ..., cmap, glyphs, kern, renders } }, woff = { ... }, ttc }
import base64, glob, json, os, subprocess
INPUTS = ["tools/fixtures/_font_reference.py"]
FONTS = os.environ.get("IMGUI_FONTS", os.path.expanduser("~/dev/luau/imgui/imgui-luau/fonts"))
PICK = ["Cousine-Regular", "DroidSans", "Karla-Regular", "ProggyClean", "Roboto-Medium"]
def generate(ctx):
specs = []
for name in PICK:
p = os.path.join(FONTS, name + ".ttf")
if os.path.exists(p):
specs.append({"name": name, "b64": base64.b64encode(open(p, "rb").read()).decode()})
out = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#source-sans"], capture_output=True,
check=True, text=True).stdout.strip().split("\n")[-1]
otf = os.path.join(out, "share", "fonts", "opentype", "SourceSans3-Regular.otf")
specs.append({"name": "SourceSans3-Regular", "b64": base64.b64encode(open(otf, "rb").read()).decode()})
code = open(os.path.join(ctx.root, "tools", "fixtures", "_font_reference.py")).read()
raw = ctx.python(["fonttools", "freetype-py", "uharfbuzz", "brotli"], code, input=json.dumps(specs).encode())
res = json.loads(raw)
d = base64.b64decode
for f in res["fonts"]:
f["data"] = d(f["data"])
for r in f["renders"]:
r["pixels"] = d(r["pixels"])
for w in res["woff"]:
w["woff"], w["woff2"], w["woff2h"] = d(w["woff"]), d(w["woff2"]), d(w["woff2h"])
if "ttc" in res:
res["ttc"]["data"] = d(res["ttc"]["data"])
ctx.emit("fonts", res)
+105
View File
@@ -0,0 +1,105 @@
# LZMA / LZMA2 / xz fixtures (tools/fixtures.py): deterministic corpora compressed by liblzma (Python's lzma module and
# the xz CLI): every preset and -e, lc / lp / pb variants, raw LZMA1 / LZMA2, .lzma files with and without the size
# and end marker, xz with every check type, BCJ (x86, PowerPC, ARM, ARM-Thumb, SPARC, ARM64) and delta filters,
# multi-block (--block-size), multi-stream and stream padding.
# tests/gen/lzma.luau { corpora = { [name] = bytes }, cases = { { name, kind, corpus, data, props?, dict?,
# size? } } } kind: "raw" (LZMA1), "raw2" (LZMA2), "alone", "xz"
# tests/gen/lzma_bench.luau { size, crc, xz, alone } (a ~4 MB corpus at -6)
import lzma, os, random, subprocess, sys, zlib
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 binary_corpus(limit):
# machine code: a slice of the Python interpreter (x86-64 here; exercises the x86 BCJ filter)
with open(os.path.realpath(sys.executable), "rb") as f:
data = f.read()
if len(data) < limit:
lib = os.path.join(os.path.dirname(os.path.realpath(sys.executable)), "..", "lib")
for name in sorted(os.listdir(lib)):
p = os.path.join(lib, name)
if name.startswith("libpython") and os.path.isfile(p):
with open(p, "rb") as f:
data += f.read(limit)
break
return data[:limit]
def xz_cli(args, data):
return subprocess.run(["xz"] + args + ["-c"], input=data, capture_output=True, check=True).stdout
def generate(ctx):
rng = random.Random(7)
corpora = {
"empty": b"",
"one": b"a",
"text": text_corpus(150000),
"binary": binary_corpus(120000),
"random": rng.randbytes(20000),
"runs": b"abc" * 3000 + b"\0" * 30000 + bytes(range(256)) * 30 + b"z" * 300,
"words": b" ".join(rng.choice([b"lorem", b"ipsum", b"dolor", b"sit", b"amet", b"\xff\xfe", b"0123"]) for _ in range(20000)),
}
cases = []
def add(name, kind, corpus, data, **extra):
c = {"name": name, "kind": kind, "corpus": corpus, "data": data}
c.update(extra)
cases.append(c)
for cname, data in corpora.items():
small = cname in ("empty", "one", "random")
presets = [0, 6] if small else [0, 1, 3, 6, 9, 9 | lzma.PRESET_EXTREME]
for p in presets:
add("%s/xz-%d%s" % (cname, p & 15, "e" if p & lzma.PRESET_EXTREME else ""), "xz", cname,
lzma.compress(data, lzma.FORMAT_XZ, check=lzma.CHECK_CRC64, preset=p))
for chk, cn in ((lzma.CHECK_NONE, "none"), (lzma.CHECK_CRC32, "crc32"), (lzma.CHECK_SHA256, "sha256")):
add("%s/xz-check-%s" % (cname, cn), "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, check=chk, preset=2))
# .lzma (alone): with a size (Python writes an end marker and no size; the CLI writes the same); raw streams
add("%s/alone" % cname, "alone", cname, lzma.compress(data, lzma.FORMAT_ALONE, preset=6))
for lc, lp, pb in ((3, 0, 2), (0, 2, 0), (4, 0, 4), (1, 3, 1), (0, 4, 3)):
f = [{"id": lzma.FILTER_LZMA1, "preset": 6, "lc": lc, "lp": lp, "pb": pb, "dict_size": 1 << 20}]
raw = lzma.compress(data, lzma.FORMAT_RAW, filters=f)
add("%s/raw-lc%d-lp%d-pb%d" % (cname, lc, lp, pb), "raw", cname, raw, props=bytes([(pb * 5 + lp) * 9 + lc]), size=len(data))
for lc, lp, pb in ((3, 0, 2), (0, 4, 4), (2, 2, 1)):
f = [{"id": lzma.FILTER_LZMA2, "preset": 6, "lc": lc, "lp": lp, "pb": pb}]
add("%s/raw2-lc%d-lp%d-pb%d" % (cname, lc, lp, pb), "raw2", cname, lzma.compress(data, lzma.FORMAT_RAW, filters=f))
if not small:
for fid, fname in ((lzma.FILTER_X86, "x86"), (lzma.FILTER_POWERPC, "ppc"), (lzma.FILTER_ARM, "arm"),
(lzma.FILTER_ARMTHUMB, "armthumb"), (lzma.FILTER_SPARC, "sparc")):
f = [{"id": fid}, {"id": lzma.FILTER_LZMA2, "preset": 3}]
add("%s/xz-%s" % (cname, fname), "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, filters=f))
f = [{"id": lzma.FILTER_X86, "start_offset": 0x1000}, {"id": lzma.FILTER_LZMA2, "preset": 3}]
add("%s/xz-x86-start" % cname, "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, filters=f))
for dist in (1, 4, 256):
f = [{"id": lzma.FILTER_DELTA, "dist": dist}, {"id": lzma.FILTER_LZMA2, "preset": 3}]
add("%s/xz-delta%d" % (cname, dist), "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, filters=f))
add("%s/xz-cli-arm64" % cname, "xz", cname, xz_cli(["--arm64", "--lzma2=preset=3"], data))
add("%s/xz-cli-blocks" % cname, "xz", cname, xz_cli(["-6", "--block-size=20000"], data))
add("%s/xz-cli-x86-delta" % cname, "xz", cname, xz_cli(["--x86", "--delta=dist=2", "--lzma2=preset=1"], data))
add("%s/alone-cli" % cname, "alone", cname, xz_cli(["--format=lzma", "-3"], data))
# multi-stream + stream padding
corpora["multi"] = corpora["text"][:40000] + corpora["runs"] + b"" + corpora["one"]
multi = (lzma.compress(corpora["text"][:40000], lzma.FORMAT_XZ, preset=1) + b"\0" * 8 +
lzma.compress(corpora["runs"], lzma.FORMAT_XZ, check=lzma.CHECK_CRC32) +
lzma.compress(b"", lzma.FORMAT_XZ) + lzma.compress(b"a", lzma.FORMAT_XZ, check=lzma.CHECK_NONE) + b"\0" * 4)
add("multi/xz-streams", "xz", "multi", multi)
ctx.emit("lzma", {"corpora": corpora, "cases": cases})
# real text and machine code, little long-range repetition
bench = text_corpus(2_000_000) + binary_corpus(1_000_000)
bench = bench[:3_000_000]
ctx.emit("lzma_bench", {"size": len(bench), "crc": zlib.crc32(bench),
"xz": lzma.compress(bench, lzma.FORMAT_XZ, preset=6),
"alone": lzma.compress(bench, lzma.FORMAT_ALONE, preset=6)})
+125
View File
@@ -0,0 +1,125 @@
# tar + gzip fixtures (tools/fixtures.py): reference archives from Python's tarfile (ustar / GNU / pax formats, long
# names, non-ASCII names, links, directories, pax mtimes) and from the host / nix GNU tar (--format=ustar / gnu /
# posix / v7), gzip members from Python's gzip and the gzip CLI (FNAME, MTIME, levels, concatenated members), and
# compressed tars (.tar.gz, .tgz, .tar.zst, .tar.xz, .tar.bz2, .tar.br) for the api's unwrap.
# tests/gen/tar.luau { files = { { name, data, ... } }, writes = { { format, entries, data } }, tars = { { name,
# data, entries = { { name, size, type, link?, mtime, mode, crc } } } }, gzips = { ... },
# wrapped = { { name, data, inner = "tar" } } }
import bz2, gzip, io, json, lzma, os, shutil, subprocess, tarfile, tempfile, zlib
def tool(name, pkg, argv, input=None, cwd=None):
exe = shutil.which(name)
cmd = ([exe] if exe else ["nix", "shell", "nixpkgs#" + pkg, "-c", name]) + argv
return subprocess.run(cmd, input=input, capture_output=True, check=True, cwd=cwd).stdout
def entries_of(data):
out = []
with tarfile.open(fileobj=io.BytesIO(data)) as t:
for m in t.getmembers():
e = {"name": m.name + ("/" if m.isdir() and not m.name.endswith("/") else ""), "type": m.type.decode() if m.type != b"\0" else "0",
"size": m.size if m.isfile() else 0, "mtime": m.mtime, "mode": m.mode}
if m.issym() or m.islnk():
e["link"] = m.linkname
if m.isfile():
e["crc"] = zlib.crc32(t.extractfile(m).read())
out.append(e)
return out
def generate(ctx):
rng = ctx.rng(5)
files = [
("hello.txt", b"hello, tar\n"),
("empty", b""),
("dir/sub/data.bin", rng.randbytes(3000)),
("exact512", bytes(range(256)) * 2),
("d" * 60 + "/" + "e" * 60 + "/long-name-over-100-bytes.txt", b"long " * 50),
("x" * 150, b"no slash to split at"),
("unicodé/naïve-ファイル.txt", "ünïcödé".encode()),
]
# the writer test: the same entries through Python's tarfile in three formats (fixed metadata)
writes = []
for fmt, pf in (("ustar", tarfile.USTAR_FORMAT), ("gnu", tarfile.GNU_FORMAT), ("pax", tarfile.PAX_FORMAT)):
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w", format=pf) as t:
ents = []
for name, data in files:
if fmt == "ustar" and (not name.isascii() or name.startswith("x" * 101)):
continue
ti = tarfile.TarInfo(name)
ti.size, ti.mtime, ti.mode, ti.uname, ti.gname = len(data), 1700000000, 0o644, "user", "group"
t.addfile(ti, io.BytesIO(data))
ents.append({"name": name, "data": data})
ti = tarfile.TarInfo("adir")
ti.type, ti.mtime, ti.mode, ti.uname, ti.gname = tarfile.DIRTYPE, 1700000000, 0o755, "user", "group"
t.addfile(ti)
ents.append({"name": "adir", "dir": True})
ti = tarfile.TarInfo("link-to-hello")
ti.type, ti.linkname, ti.mtime, ti.mode, ti.uname, ti.gname = tarfile.SYMTYPE, "hello.txt", 1700000000, 0o777, "user", "group"
t.addfile(ti)
ents.append({"name": "link-to-hello", "type": "2", "link": "hello.txt", "mode": 0o777})
writes.append({"format": fmt, "entries": ents, "data": buf.getvalue()})
tars = []
for w in writes:
tars.append({"name": "python-" + w["format"], "data": w["data"], "entries": entries_of(w["data"])})
# pax with a fractional mtime and a huge uid
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w", format=tarfile.PAX_FORMAT) as t:
ti = tarfile.TarInfo("frac.txt")
ti.size, ti.mtime, ti.uid = 3, 1600000000.5, 3000000
t.addfile(ti, io.BytesIO(b"abc"))
tars.append({"name": "python-pax-extras", "data": buf.getvalue(), "entries": entries_of(buf.getvalue())})
# GNU tar on a real tree
tmp = tempfile.mkdtemp()
try:
root = os.path.join(tmp, "tree")
for name, data in files:
p = os.path.join(root, name)
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "wb") as f:
f.write(data)
os.makedirs(os.path.join(root, "emptydir"))
os.symlink("hello.txt", os.path.join(root, "sym"))
os.link(os.path.join(root, "hello.txt"), os.path.join(root, "hard"))
for dirpath, dirs, fs in os.walk(root):
for n in dirs + fs:
os.utime(os.path.join(dirpath, n), (1650000000, 1650000000), follow_symlinks=False)
for fmt in ("ustar", "gnu", "posix", "v7"):
argv = ["--format=" + fmt, "--sort=name", "--owner=0", "--group=0", "--numeric-owner", "-cf", "-", "."]
if fmt in ("ustar", "v7"):
argv = ["--exclude=./" + "x" * 150, "--exclude=./d" + "d" * 59] + argv
if fmt == "v7":
argv = ["--exclude=./unicodé"] + argv
data = tool("tar", "gnutar", argv, cwd=root)
tars.append({"name": "gnutar-" + fmt, "data": data, "entries": entries_of(data)})
finally:
shutil.rmtree(tmp)
# gzip
text = ("The quick brown fox jumps over the lazy dog. " * 300).encode()
gzips = []
b = io.BytesIO()
with gzip.GzipFile(filename="story.txt", mode="wb", fileobj=b, mtime=1234567890, compresslevel=9) as g:
g.write(text)
gzips.append({"name": "python-fname", "data": b.getvalue(), "entry": "story.txt", "mtime": 1234567890, "crc": zlib.crc32(text), "size": len(text)})
gzips.append({"name": "python-noname", "data": gzip.compress(text, 1, mtime=0), "entry": "data", "mtime": 0, "crc": zlib.crc32(text), "size": len(text)})
cli = tool("gzip", "gzip", ["-9", "-n", "-c"], input=text)
gzips.append({"name": "cli-n", "data": cli, "entry": "data", "mtime": 0, "crc": zlib.crc32(text), "size": len(text)})
two = gzip.compress(text[:1000], mtime=0) + gzip.compress(text[1000:], mtime=0)
gzips.append({"name": "members", "data": two, "entry": "data", "mtime": 0, "crc": zlib.crc32(text), "size": len(text)})
# compressed tars
inner = writes[2]["data"]
wrapped = [
{"name": "a.tar.gz", "data": gzip.compress(inner, mtime=0), "outer": "gzip"},
{"name": "a.tgz", "data": tool("gzip", "gzip", ["-c", "-n"], input=inner), "outer": "gzip"},
{"name": "a.tar.bz2", "data": bz2.compress(inner), "outer": "bz2"},
{"name": "a.tar.xz", "data": lzma.compress(inner), "outer": "xz"},
{"name": "a.tar.zst", "data": tool("zstd", "zstd", ["-c", "-q"], input=inner), "outer": "zst"},
{"name": "a.tar.br", "data": ctx.python(["brotli"], "import brotli, sys; sys.stdout.buffer.write(brotli.compress(sys.stdin.buffer.read()))", input=inner), "outer": "br"},
]
ctx.emit("tar", {"files": [{"name": n, "data": d} for n, d in files], "writes": writes, "tars": tars,
"gzips": gzips, "wrapped": wrapped, "innerEntries": entries_of(inner)})
+85
View File
@@ -0,0 +1,85 @@
# Zstd fixtures (tools/fixtures.py): deterministic corpora compressed with the zstd CLI (the reference) at levels
# 1..19 and --ultra -22, --long, small windows (small blocks), with / without the content checksum, with / without the
# content size (stdin), multi-frame and skippable-frame streams, and empty input; plus a ~6 MB bench corpus.
# tests/gen/zstd.luau { corpora = { [name] = bytes }, cases = { { name, corpus, data } } }
# tests/gen/zstd_bench.luau { size, data3, data19, crc }
import os, random, shutil, subprocess, tempfile, zlib
def generate(ctx):
rng = random.Random(7)
def zstd(args, data, from_file=True):
exe = shutil.which("zstd")
if from_file:
with tempfile.TemporaryDirectory() as d:
p = os.path.join(d, "in")
with open(p, "wb") as f:
f.write(data)
argv = ["zstd", "-q", "-c"] + args + [p]
if exe:
return subprocess.run([exe] + argv[1:], capture_output=True, check=True).stdout
return ctx.nix("zstd", argv)
argv = ["zstd", "-q", "-c"] + args
if exe:
return subprocess.run([exe] + argv[1:], input=data, capture_output=True, check=True).stdout
return ctx.nix("zstd", argv, input=data)
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])
text = text_corpus(400000)
corpora = {
"empty": b"",
"one": b"a",
"short": b"hello, hello, hello zstd world\n",
"text": text[:200000],
"random": rng.randbytes(50000),
"runs": b"abc" * 4000 + b"\0" * 20000 + bytes(range(256)) * 40 + b"z" * 300,
"far": (lambda r: r + rng.randbytes(30000) + r)(rng.randbytes(20000)),
"binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(60000)),
"mixed": bytes(rng.choice(b"aaaaabbbcd\n") for _ in range(30000)) + rng.randbytes(3000) + text[200000:300000],
"big": (text + bytes(rng.choice(b"\0\0\x01\x02\x03xyz") for _ in range(200000))),
}
cases = [] # (name, corpus, data)
for cname, data in corpora.items():
levels = [1, 3, 19] if cname in ("big",) else [1, 2, 3, 5, 7, 9, 12, 15, 17, 19]
for lv in levels:
cases.append(("%s/l%d" % (cname, lv), cname, zstd(["-%d" % lv], data)))
if cname != "big":
cases.append(("%s/ultra22" % cname, cname, zstd(["--ultra", "-22"], data)))
cases.append(("%s/long" % cname, cname, zstd(["--long=24", "-9"], data)))
cases.append(("%s/negative" % cname, cname, zstd(["--fast=3"], data)))
cases.append(("%s/wlog10" % cname, cname, zstd(["--zstd=wlog=10", "-6"], data)))
cases.append(("%s/nocheck" % cname, cname, zstd(["-5", "--no-check"], data)))
cases.append(("%s/stdin" % cname, cname, zstd(["-4", "--check"], data, from_file=False)))
# several frames, a skippable frame between them, and a skippable frame first
t = corpora["text"]
skip = (0x184D2A53).to_bytes(4, "little") + (11).to_bytes(4, "little") + b"skip me now"
multi = zstd(["-3"], t[:50000]) + skip + zstd(["-1", "--no-check"], corpora["runs"]) + zstd(["-3"], b"") + zstd(["-19"], t[50000:90000])
corpora["multi"] = t[:50000] + corpora["runs"] + t[50000:90000]
cases.append(("multi/frames", "multi", multi))
corpora["skipfirst"] = corpora["short"]
cases.append(("skipfirst/frames", "skipfirst", skip + zstd(["-3"], corpora["short"]) + skip))
ctx.emit("zstd", {
"corpora": corpora,
"cases": [{"name": n, "corpus": c, "data": d} for n, c, d in cases],
})
bench = bytearray()
while len(bench) < 6_000_000:
bench += text + bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(100000)) + rng.randbytes(20000)
bench = bytes(bench[:6_000_000])
ctx.emit("zstd_bench", {"size": len(bench), "crc": zlib.crc32(bench), "data3": zstd(["-3"], bench),
"data19": zstd(["-19"], bench)})