Files
rosetta/tools/fixtures/lz4.py
T

91 lines
4.1 KiB
Python

# LZ4 block fixtures (tools/fixtures.py): deterministic corpora compressed by the reference (python-lz4, the lz4
# library: fast mode at several accelerations, and HC at levels 4 / 9 / 12), plus our own encoder's blocks
# (tools/fixtures/_lz4_encode.luau under the luau CLI) decompressed by the reference, as verdicts.
# tests/gen/lz4.luau { corpora = { [name] = bytes }, cases = { { name, corpus, data } }, ours = { { name, ok } } }
# tests/gen/lz4_bench.luau { size, crc, data (lz4 HC 9 block), raw }
import json, os, random, shutil, subprocess, zlib
INPUTS = ["src/Formats/codecs/compress/Lz4.luau", "tools/fixtures/_lz4_encode.luau"]
REF = r"""
import json, sys, lz4.block
req = json.load(sys.stdin)
out = {}
if req["op"] == "compress":
for name, hexdata in req["corpora"].items():
data = bytes.fromhex(hexdata)
res = {}
for acc in (1, 4, 16):
res["fast%d" % acc] = lz4.block.compress(data, mode="fast", acceleration=acc, store_size=False).hex()
for lv in (4, 9, 12):
res["hc%d" % lv] = lz4.block.compress(data, mode="high_compression", compression=lv, store_size=False).hex()
out[name] = res
else:
for name, item in req["blocks"].items():
try:
got = lz4.block.decompress(bytes.fromhex(item["data"]), uncompressed_size=item["size"])
out[name] = got.hex() == item["want"]
except Exception as e:
out[name] = False
print(json.dumps(out))
"""
def corpora(rng):
base = os.path.dirname(os.__file__)
text = bytearray()
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) >= 300000:
break
text = bytes(text[:300000])
far = rng.randbytes(9000)
return {
"empty": b"",
"one": b"a",
"twelve": b"abcabcabcabc",
"thirteen": b"abcabcabcabca",
"short": b"hello, hello, hello lz4 world\n",
"text": text[:150000],
"random": rng.randbytes(20000),
"runs": b"abc" * 4000 + b"\0" * 70000 + bytes(range(256)) * 40 + b"z" * 300,
"zeros": b"\0" * 100000,
"far": far + rng.randbytes(60000) + far,
"binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(60000)),
"longlit": rng.randbytes(1000) + b"q" * 1000 + rng.randbytes(300),
}
def luau_cmd():
exe = shutil.which("luau")
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
def generate(ctx):
rng = random.Random(41)
cs = corpora(rng)
ref = json.loads(ctx.python(["lz4"], REF, input=json.dumps({"op": "compress", "corpora": {k: v.hex() for k, v in cs.items()}}).encode()))
cases = []
for name, res in ref.items():
for mode, hexdata in res.items():
cases.append({"name": "%s/%s" % (name, mode), "corpus": name, "data": bytes.fromhex(hexdata)})
# our encoder's blocks, read back by the reference
ctx.emit("lz4_corpora", cs)
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_lz4_encode.luau")], capture_output=True, check=True, cwd=ctx.root).stdout.decode()
blocks = {}
for line in enc.split("\n"):
if line.strip():
name, hexdata = line.split(" ", 1)
blocks[name] = {"data": hexdata.strip(), "size": len(cs[name]), "want": cs[name].hex()}
verdict = json.loads(ctx.python(["lz4"], REF, input=json.dumps({"op": "decompress", "blocks": blocks}).encode()))
ours = [{"name": n, "ok": bool(verdict.get(n)), "size": len(bytes.fromhex(blocks[n]["data"]))} for n in sorted(blocks)]
ctx.emit("lz4", {"cases": cases, "ours": ours})
bench = bytearray()
while len(bench) < 6_000_000:
bench += cs["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])
code = "import sys, lz4.block; sys.stdout.buffer.write(lz4.block.compress(sys.stdin.buffer.read(), mode='high_compression', compression=9, store_size=False))"
ctx.emit("lz4_bench", {"size": len(bench), "crc": zlib.crc32(bench), "data": ctx.python(["lz4"], code, input=bench)})