ws-roblox: codecs/compress/Lz4 (LZ4 block decode + encode, decodeInto with history for linked blocks), tests vs python-lz4 both ways, bench line

This commit is contained in:
4DBug committed 2026-10-31 13:53:23 -05:00
1 parent de4f14a343
commit 1ed25296ba
6 files changed
+510 -1

No files matched your search

+1
View File
@@ -103,6 +103,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
- codecs/compress/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written
- codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec
- codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md): decode and a greedy hash-chain-free encoder
- codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3):
- codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and
- codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD / PSB RLE channels, IFF
+291
View File
@@ -0,0 +1,291 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md): decode and a greedy hash-chain-free encoder
-- (the reference "fast" strategy: one 4-byte hash table, 64 KB window). A codec (layer 3): model/rbxm chunk bodies,
-- and the LZ4 frame format (archive) builds on it. New code, written from the specification. Never throws.
--
-- local out, err = Lz4.decompress(src, offset?, length?, outSize?, opts?) -- a block -> buffer | nil, Err
-- local packed = Lz4.compress(src, offset?, length?) -- -> buffer (a block) | nil, Err
-- local dEnd, msg = Lz4.decodeInto(src, p, limit, dst, d, dstLimit, histStart?) -- low level (linked blocks)
-- local n = Lz4.encodeInto(src, p, n, dst, d) -- low level; dst has bound(n) room
-- Lz4.bound(n) -- worst-case block size for n bytes
--
-- decodeInto decodes one block from src[p, limit) to dst[d, dstLimit): matches may reach back to histStart (default
-- d), so a frame decoder with linked blocks keeps the previous output in front of d. It returns the output end, or
-- nil and a message ("truncated", "corrupt: ...", "limit: output ...") for the caller's Err.from.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Lz4 = {}
export type Options = {
maxBytes: number?, -- refuse output larger than this when outSize is not given (default 2^28)
}
local readu8, writeu8, readu16, writeu16, readu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32
local bcopy, bcreate, blen = buffer.copy, buffer.create, buffer.len
local band, rshift = bit32.band, bit32.rshift
local MINMATCH = 4
local LASTLITERALS = 5 -- the last 5 bytes are always literals
local MFLIMIT = 12 -- the last match starts at least 12 bytes before the end
local MAX_OFFSET = 65535
local HASH_BITS = 13
local HASH_SIZE = 2 ^ HASH_BITS
-- ------------------------------------------------------------------------------------------------ decode
function Lz4.decodeInto(src: buffer, p: number, limit: number, dst: buffer, d: number, dstLimit: number, histStart: number?): (number?, string?)
local lo = histStart or d
if limit > blen(src) or dstLimit > blen(dst) or p < 0 or d < 0 or lo < 0 or lo > d then
return nil, "corrupt: bad ranges"
end
if p >= limit then
return nil, "truncated: empty block"
end
while true do
if p >= limit then
return nil, "truncated"
end
local token = readu8(src, p)
p += 1
local lit = rshift(token, 4)
if lit == 15 then
local b = 255
while b == 255 do
if p >= limit then
return nil, "truncated"
end
b = readu8(src, p)
p += 1
lit += b
end
end
if lit > 0 then
if p + lit > limit then
return nil, "truncated: literals past the end"
end
if d + lit > dstLimit then
return nil, "limit: output larger than expected"
end
bcopy(dst, d, src, p, lit)
p += lit
d += lit
end
if p >= limit then
return d, nil -- the last sequence has no match
end
if p + 2 > limit then
return nil, "truncated"
end
local off = readu16(src, p)
p += 2
if off == 0 or d - off < lo then
return nil, "corrupt: bad match offset"
end
local ml = band(token, 15)
if ml == 15 then
local b = 255
while b == 255 do
if p >= limit then
return nil, "truncated"
end
b = readu8(src, p)
p += 1
ml += b
end
end
ml += MINMATCH
if d + ml > dstLimit then
return nil, "limit: output larger than expected"
end
local s = d - off
if off >= ml then
bcopy(dst, d, dst, s, ml)
d += ml
elseif off == 1 then
buffer.fill(dst, d, readu8(dst, s), ml)
d += ml
else
-- an overlapping match repeats the off-byte pattern: copy what is already there, doubling each time
local n = ml
while n > 0 do
local c = d - s
if c > n then
c = n
end
bcopy(dst, d, dst, s, c)
d += c
n -= c
end
end
end
end
-- decompress(src, offset?, length?, outSize?, opts?) -> buffer | nil, Err: one block. With outSize the output must be
-- exactly that long (CORRUPT otherwise); without it the output grows up to opts.maxBytes.
function Lz4.decompress(src: buffer | string, offset: number?, length: number?, outSize: number?, opts: Options?): (buffer?, Err.Err?)
local b, o, l, aerr = Bytes.span("Lz4.decompress", src, offset, length)
if not b then
return nil, aerr
end
if outSize ~= nil then
if type(outSize) ~= "number" or outSize < 0 or outSize % 1 ~= 0 then
return nil, Err.new(Err.ARG, "Lz4.decompress: bad outSize")
end
local out = bcreate(outSize)
local e, msg = Lz4.decodeInto(b, o, o + l, out, 0, outSize)
if not e then
return nil, Err.from(msg, o)
end
if e ~= outSize then
return nil, Err.new(Err.CORRUPT, string.format("block decodes to %d bytes, expected %d", e, outSize), o)
end
return out, nil
end
local max = (opts and opts.maxBytes) or 2 ^ 28
local size = math.min(math.max(l * 4, 256), max)
while true do
local out = bcreate(size)
local e, msg = Lz4.decodeInto(b, o, o + l, out, 0, size)
if e then
local res = bcreate(e)
bcopy(res, 0, out, 0, e)
return res, nil
end
if not (msg and string.sub(msg, 1, 6) == "limit:") then
return nil, Err.from(msg, o)
end
if size >= max then
return nil, Err.new(Err.LIMIT, "output over " .. max .. " bytes", o)
end
size = math.min(size * 4, max)
end
end
-- ------------------------------------------------------------------------------------------------ encode
-- bound(n) -> the largest block n input bytes can produce
function Lz4.bound(n: number): number
return n + n // 255 + 16
end
-- writes a length's 255-run extension at o; returns the next offset
local function extend(dst: buffer, o: number, n: number): number
while n >= 255 do
writeu8(dst, o, 255)
o += 1
n -= 255
end
writeu8(dst, o, n)
return o + 1
end
-- hash(v) -> 1 .. HASH_SIZE: Knuth's multiplicative hash (v * 2654435761 mod 2^32, top bits), exact in doubles
local function hash(v: number): number
local vl, vh = band(v, 0xFFFF), rshift(v, 16)
local mid = (vh * 0x79B1 + vl * 0x9E37) % 65536
return ((vl * 0x79B1 + mid * 65536) % 4294967296) // (2 ^ (32 - HASH_BITS)) + 1
end
local hashTable: { number } = table.create(HASH_SIZE, -1e9)
-- encodeInto(src, p, n, dst, d) -> the block's length: src[p, p + n) compressed to dst[d ..] (room for bound(n))
function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: number): number
local op = d
local anchor = p
local iend = p + n
local ht = hashTable
for i = 1, HASH_SIZE do
ht[i] = -1e9
end
if n >= MFLIMIT + 1 then
local mflimit = iend - MFLIMIT -- a match starts before this
local matchEnd = iend - LASTLITERALS -- and ends at or before this
local ip = p
local skip = 64
while ip < mflimit do
local v = readu32(src, ip)
local h = hash(v)
local ref = ht[h]
ht[h] = ip
if ref >= p and ip - ref <= MAX_OFFSET and readu32(src, ref) == v then
-- back over equal bytes before the match (into the pending literals)
while ip > anchor and ref > p and readu8(src, ip - 1) == readu8(src, ref - 1) do
ip -= 1
ref -= 1
end
local a = ip + MINMATCH
local bpos = ref + MINMATCH
while a + 4 <= matchEnd and readu32(src, a) == readu32(src, bpos) do
a += 4
bpos += 4
end
while a < matchEnd and readu8(src, a) == readu8(src, bpos) do
a += 1
bpos += 1
end
local ml = a - ip
local lit = ip - anchor
local tok = op
op += 1
local tl = if lit >= 15 then 15 else lit
if lit >= 15 then
op = extend(dst, op, lit - 15)
end
if lit > 0 then
bcopy(dst, op, src, anchor, lit)
op += lit
end
writeu16(dst, op, ip - ref)
op += 2
local m = ml - MINMATCH
local tm = if m >= 15 then 15 else m
if m >= 15 then
op = extend(dst, op, m - 15)
end
writeu8(dst, tok, tl * 16 + tm)
ip = a
anchor = ip
skip = 64
-- index the position just before the next one (better ratio at no cost)
if ip - 2 >= p and ip - 2 < mflimit then
local w = readu32(src, ip - 2)
ht[hash(w)] = ip - 2
end
else
ip += rshift(skip, 6) -- step up over incompressible data (the reference's acceleration)
skip += 1
end
end
end
-- the last literals
local lit = iend - anchor
local tok = op
op += 1
if lit >= 15 then
op = extend(dst, op, lit - 15)
writeu8(dst, tok, 0xF0)
else
writeu8(dst, tok, lit * 16)
end
if lit > 0 then
bcopy(dst, op, src, anchor, lit)
op += lit
end
return op - d
end
-- compress(src, offset?, length?) -> buffer (one block) | nil, Err
function Lz4.compress(src: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?)
local b, o, l, aerr = Bytes.span("Lz4.compress", src, offset, length)
if not b then
return nil, aerr
end
local tmp = bcreate(Lz4.bound(l))
local n = Lz4.encodeInto(b, o, l, tmp, 0)
local out = bcreate(n)
bcopy(out, 0, tmp, 0, n)
return out, nil
end
return Lz4
+101
View File
@@ -0,0 +1,101 @@
-- codecs/compress/Lz4 tests: every reference block (python-lz4 fast at accelerations 1 / 4 / 16, HC 4 / 9 / 12)
-- decodes to its corpus, with and without the size; our encoder's blocks decode with the reference (fixture verdicts)
-- and round trip here; linked blocks through decodeInto's history; error codes; truncated / mutated / random blocks
-- never throw. Fixtures: tools/fixtures/lz4.py.
local T = require("@tests/T")
local Lz4 = require("@formats/codecs/compress/Lz4")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/lz4")
local C = require("@tests/gen/lz4_corpora")
local t = T.suite("lz4")
local nbytes = 0
for _, c in Fx.cases do
local want = C[c.corpus]
local out, err = Lz4.decompress(c.data, nil, nil, #want)
t:check(out ~= nil and buffer.tostring(out) == want, c.name .. ": " .. tostring(err))
if #want > 0 then
local grown = Lz4.decompress(c.data)
t:check(grown ~= nil and buffer.tostring(grown) == want, c.name .. ": without the size")
end
nbytes += #want
end
t:note("%d reference blocks, %.1f MB decoded", #Fx.cases, nbytes / 1e6)
for _, v in Fx.ours do
t:check(v.ok, v.name .. ": the reference decodes our block")
end
for name, data in C do
local b = Lz4.compress(data) :: buffer
local back = Lz4.decompress(b, nil, nil, #data)
t:check(back ~= nil and buffer.tostring(back) == data, name .. ": round trip")
if name == "text" or name == "zeros" or name == "runs" then
t:check(buffer.len(b) < #data / 2, name .. ": compresses")
end
t:check(buffer.len(b) <= Lz4.bound(#data), name .. ": within bound")
end
-- at an offset, and linked blocks: the second block refers into the first one's output
do
local text = C.text
local a, b2 = string.sub(text, 1, 70000), string.sub(text, 70001, 140000)
local pa = Lz4.compress(a) :: buffer
-- a block of b2 that copies the first 40 bytes of b2's region from a (a match reaching back across blocks)
local big = buffer.create(buffer.len(pa) + 20)
buffer.copy(big, 9, pa)
local out = Lz4.decompress(big, 9, buffer.len(pa), #a)
t:check(out ~= nil and buffer.tostring(out) == a, "at an offset")
local hand = buffer.create(3 + 1 + 2 + 1)
-- token: 0 literals, match length 15 + ext; offset = 100 back into the previous block
buffer.writeu8(hand, 0, 0x0F)
buffer.writeu16(hand, 1, 100)
buffer.writeu8(hand, 3, 20) -- match length 4 + 15 + 20 = 39
buffer.writeu8(hand, 4, 0x10) -- the last sequence: one literal
buffer.writeu8(hand, 5, 33)
local dst = buffer.create(#a + 40)
buffer.writestring(dst, 0, a)
local e, msg = Lz4.decodeInto(hand, 0, 6, dst, #a, #a + 40, 0)
t:check(e == #a + 40, "linked block: " .. tostring(msg))
t:eq(buffer.readstring(dst, #a, 39), string.sub(a, #a - 99, #a - 61), "linked block: match from the history")
local e2, msg2 = Lz4.decodeInto(hand, 0, 6, dst, #a, #a + 40)
t:check(e2 == nil and string.find(msg2 or "", "offset") ~= nil, "without history the match is corrupt")
t:check(b2 ~= nil, "second half")
end
-- errors
do
local _, e1 = Lz4.decompress("")
t:check(e1 and e1.code == Err.TRUNCATED, "empty: " .. tostring(e1))
local _, e2 = Lz4.decompress("\x50ab")
t:check(e2 and e2.code == Err.TRUNCATED, "literals past the end: " .. tostring(e2))
local _, e3 = Lz4.decompress("\x14abcd\x09\x00\x10z")
t:check(e3 and e3.code == Err.CORRUPT, "offset before the start: " .. tostring(e3))
local _, e4 = Lz4.decompress("\x10a", nil, nil, 5)
t:check(e4 and e4.code == Err.CORRUPT, "shorter than outSize: " .. tostring(e4))
local _, e5 = Lz4.decompress("\x50abcde", nil, nil, 2)
t:check(e5 and e5.code == Err.LIMIT, "longer than outSize: " .. tostring(e5))
local _, e6 = Lz4.decompress(C.zeros and (Lz4.compress(C.zeros) :: buffer), nil, nil, nil, { maxBytes = 1000 })
t:check(e6 and e6.code == Err.LIMIT, "maxBytes: " .. tostring(e6))
local ok, r1, r2 = pcall(Lz4.decompress, 5 :: any)
t:check(ok and r1 == nil and r2.code == Err.ARG, "a non-buffer argument returns Err.ARG")
local _, e7 = Lz4.decompress("\x10a", nil, nil, -1)
t:check(e7 and e7.code == Err.ARG, "bad outSize")
end
do
local samples = {}
for i, c in Fx.cases do
if i % 4 == 0 and #c.data > 8 and #c.data < 30000 then
table.insert(samples, c.data)
end
end
t:fuzz("decompress", function(b: buffer)
return Lz4.decompress(b, nil, nil, nil, { maxBytes = 1e6 })
end, samples, { mutations = 30, garbage = 2000 })
t:fuzz("decompress (sized)", function(b: buffer)
return Lz4.decompress(b, nil, nil, 70000)
end, samples, { mutations = 30, garbage = 500, seed = 5 })
end
t:done()
+14 -1
View File
@@ -1,7 +1,7 @@
-- Throughput (bash tools/bench.sh): codec MB/s under both runtimes. MB/s are of decompressed output, best of n runs.
-- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus), tools/fixtures/png.py (1024 x 768 images), tools/fixtures/mp3.py,
-- tools/fixtures/opus.py (3 s stereo files; MB/s of f32 output, 48 kHz stereo f32 is 0.384 MB/s of real time),
-- tools/fixtures/flac.py; wav encodes / decodes a generated tone; zstd / brotli / bzip2 / lzma (*_bench corpora), fonts
-- tools/fixtures/flac.py; wav encodes / decodes a generated tone; zstd / brotli / bzip2 / lzma / lz4 (*_bench corpora), fonts
-- (glyphs per second), json / xml / yaml, jpeg / gif / tiff / qoi / tga / pnm / hdr and ImageOps.
local Deflate = require("@formats/codecs/compress/Deflate")
local Crc32 = require("@formats/core/Crc32")
@@ -236,6 +236,19 @@ do
Zstd.decompress(z19, nil, nil, { verify = false })
end)
end
do
local Lz4 = require("@formats/codecs/compress/Lz4")
local LB = require("@tests/gen/lz4_bench")
local lz = buffer.fromstring(LB.data)
local raw = assert(Lz4.decompress(lz, nil, nil, LB.size))
assert(Crc32.of(raw) == LB.crc, "lz4 bench corpus mismatch")
bench("lz4 block decompress (hc9)", 5, LB.size, function()
Lz4.decompress(lz, nil, nil, LB.size)
end)
bench("lz4 block compress", 3, LB.size, function()
Lz4.compress(raw)
end)
end
do
local Brotli = require("@formats/codecs/compress/Brotli")
local BB = require("@tests/gen/brotli_bench")
+13
View File
@@ -0,0 +1,13 @@
-- tools/fixtures/_lz4_encode.luau: run by tools/fixtures/lz4.py under the luau CLI: compresses every corpus of
-- tests/gen/lz4_corpora with codecs/compress/Lz4 and prints "<name> <hex>" lines for the reference to decompress.
local Lz4 = require("@formats/codecs/compress/Lz4")
local C = require("@tests/gen/lz4_corpora")
for name, data in C do
local b = assert(Lz4.compress(data))
local t = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
t[i + 1] = string.format("%02x", buffer.readu8(b, i))
end
print(name .. " " .. table.concat(t))
end
+90
View File
@@ -0,0 +1,90 @@
# 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)})