diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 181230b..8b4da14 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,7 +6,9 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| | image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | +| archive | zst | .zst .tzst | yes | - | stream: true | `tests/archive/zst.luau` | Codecs (layer 1, shared by formats; not loadable on their own): - codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. +- codecs/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ba09f70..36ba223 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -26,6 +26,18 @@ local list: { Entry } = { return require("@formats/image/png") end, }, + { + name = "zst", + category = "archive", + path = "archive/zst", + extensions = { "zst", "tzst" }, + mime = { "application/zstd" }, + deps = { "core/Err", "core/Bytes", "codecs/Zstd", "containers/Archive" }, + caps = { decode = true, encode = false, stream = true }, + load = function() + return require("@formats/archive/zst") + end, + }, } return list diff --git a/src/Formats/archive/zst/init.luau b/src/Formats/archive/zst/init.luau new file mode 100644 index 0000000..af5eef6 --- /dev/null +++ b/src/Formats/archive/zst/init.luau @@ -0,0 +1,63 @@ +--!strict +-- archive/zst: a Zstandard-compressed file (.zst, RFC 8878) as a single-stream archive holding one entry, decoded +-- through codecs/Zstd. The entry is named after the file without its extension (opts.name; ".tzst" -> ".tar"), else +-- "data". The api unwraps it when the entry is itself an archive (.tar.zst loads as the tar). Read-only. +-- Not supported: dictionaries, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Zstd = require("@formats/codecs/Zstd") +local Archive = require("@formats/containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Zst = { + name = "zst", + category = "archive", + extensions = { "zst", "tzst" }, + mime = { "application/zstd" }, + deps = { "core/Err", "core/Bytes", "codecs/Zstd", "containers/Archive" }, + caps = { decode = true, encode = false, stream = true }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse a decompressed size over this (default 2^30) + verify: boolean?, -- check the content checksum (default true) + name: string?, -- the file name, for the entry name (the api passes it) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Zst.sniff(r: Bytes.Reader): number + local m = r:peek(4) + if m == Zstd.MAGIC then + return 1 + end + -- a skippable frame (0x184D2A50 .. 0x184D2A5F) is usually followed by a zstd frame + if #m == 4 and string.sub(m, 2, 4) == "\42\77\24" and bit32.band(string.byte(m, 1), 0xF0) == 0x50 then + return 0.5 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Zst.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local len = r.limit - r.base + local out, err = Zstd.decompress(r.buf, r.base, len, { maxBytes = o.maxBytes, verify = o.verify }) + if not out then + return nil, err + end + local a = Archive.new("zst") + a.meta.stream = true + Archive.put(a, { + name = Archive.streamName(o, Zst.extensions), + size = buffer.len(out), + compressedSize = len, + method = "zstd", + dir = false, + data = out, + }) + return a, nil +end + +return Zst diff --git a/src/Formats/codecs/Zstd/Decode.luau b/src/Formats/codecs/Zstd/Decode.luau new file mode 100644 index 0000000..7ad77d5 --- /dev/null +++ b/src/Formats/codecs/Zstd/Decode.luau @@ -0,0 +1,980 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Zstd/Decode: Zstandard frame decoder (RFC 8878), written from the specification (no code copied from the +-- BSD reference implementation). Frames (any number, concatenated), skippable frames, raw / RLE / compressed blocks, +-- Huffman literals (1 or 4 streams, new or repeated table), FSE sequence tables (predefined / RLE / compressed / +-- repeat), repeat offsets, the XXH64 content checksum. Not supported: dictionaries (a non-zero dictionary ID). +-- +-- The whole output lives in one buffer, so the window is the output itself (offsets are checked against the frame's +-- start). Backward bitstreams are read through bit offsets: bits [o - n, o) of a stream come from one readu32 at +-- byte (o - n) / 8, bits before the stream start read as zeros. +-- +-- Nothing here throws on any input: every read is bounds-checked; failures return nil, code, message, offset. +local Xxh64 = require("@formats/codecs/Zstd/Xxh64") + +local band, lshift, rshift = bit32.band, bit32.lshift, bit32.rshift +local readu8, readu16, readu32, writeu8, writeu16, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32 +local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len + +local MAGIC = 0xFD2FB528 +local BLOCK_MAX = 131072 + +local Decode = {} + +-- ------------------------------------------------------------------------------------------------ tables +-- literal length / match length codes: baseline, extra bits (index = code + 1) +local LL_BASE = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 24, 28, 32, 40, 48, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536 } +local LL_BITS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 } +local ML_BASE = { + 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, + 35, 37, 39, 41, 43, 47, 51, 59, 67, 83, 99, 131, 259, 515, 1027, 2051, 4099, 8195, 16387, 32771, 65539, +} +local ML_BITS = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, +} +local LL_DEFAULT = { 4, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 1, -1, -1, -1, -1 } +local ML_DEFAULT = { + 1, 4, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, +} +local OF_DEFAULT = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1 } + +-- highest set bit of 1..2048 +local HB = table.create(2048, 0) +do + local v = 0 + for i = 1, 2048 do + if i >= lshift(2, v) then + v += 1 + end + HB[i] = v + end +end + +-- ------------------------------------------------------------------------------------------------ bit readers +-- backward stream starting at byte s: bits [o - n, o) (n <= 25), bits below 0 are zeros +local function peek(b: buffer, s: number, o: number, n: number): number + if n <= 0 then + return 0 + end + local lo = o - n + if lo >= 0 then + local byte = s + rshift(lo, 3) + local bl = blen(b) + if byte + 4 <= bl then + return band(rshift(readu32(b, byte), band(lo, 7)), lshift(1, n) - 1) + end + local v = 0 + local m = 1 + for k = 0, 3 do + if byte + k < bl then + v += readu8(b, byte + k) * m + end + m *= 256 + end + return band(rshift(v, band(lo, 7)), lshift(1, n) - 1) + end + if o <= 0 then + return 0 + end + return lshift(peek(b, s, o, o), -lo) +end + +-- the bit length of a backward stream [s, e) (up to its end marker), or -1 when the last byte is 0 / it is empty +local function streamBits(b: buffer, s: number, e: number): number + if e <= s then + return -1 + end + local last = readu8(b, e - 1) + if last == 0 then + return -1 + end + return (e - 1 - s) * 8 + HB[last] +end + +-- forward stream: n (<= 24) bits at bit position bp from byte p; bytes at or past e read as zeros +local function getF(b: buffer, p: number, e: number, bp: number, n: number): number + local byte = p + rshift(bp, 3) + local v = 0 + local m = 1 + for k = 0, 3 do + if byte + k < e then + v += readu8(b, byte + k) * m + end + m *= 256 + end + return band(rshift(v, band(bp, 7)), lshift(1, n) - 1) +end + +-- ------------------------------------------------------------------------------------------------ FSE +-- FSE decoding table entries (u32): symbol | nbBits << 8 | newStateBase << 16 +local symTmp = bcreate(512) + +-- build(norm, nsym, al, t) -> true | nil, message. norm: { [symbol + 1] = normalized count (-1 = "less than 1") } +local function buildFse(norm: { number }, nsym: number, al: number, t: buffer): (boolean?, string?) + local size = lshift(1, al) + local high = size - 1 + local next = table.create(nsym, 0) + for s = 0, nsym - 1 do + local c = norm[s + 1] + if c == -1 then + if high < 0 then + return nil, "bad FSE distribution" + end + writeu8(symTmp, high, s) + high -= 1 + next[s + 1] = 1 + else + next[s + 1] = c + end + end + local pos = 0 + local step = rshift(size, 1) + rshift(size, 3) + 3 + local mask = size - 1 + for s = 0, nsym - 1 do + local c = norm[s + 1] + for _ = 1, c do + writeu8(symTmp, pos, s) + local guard = 0 + repeat + pos = band(pos + step, mask) + guard += 1 + until pos <= high or guard > size + if guard > size then + return nil, "bad FSE distribution" + end + end + end + if pos ~= 0 then + return nil, "bad FSE distribution" + end + for u = 0, size - 1 do + local s = readu8(symTmp, u) + local ns = next[s + 1] + if ns < 1 or ns > 2048 then + return nil, "bad FSE distribution" + end + next[s + 1] = ns + 1 + local nb = al - HB[ns] + if nb < 0 then + return nil, "bad FSE distribution" + end + writeu32(t, u * 4, s + nb * 256 + (lshift(ns, nb) - size) * 65536) + end + return true, nil +end + +-- ncount(b, p, e, maxSym, maxAL, norm) -> al, bytesUsed, nsym | nil, message: an FSE table description +local function ncount(b: buffer, p: number, e: number, maxSym: number, maxAL: number, norm: { number }): (number?, any, number?) + if p >= e then + return nil, "truncated FSE table" + end + local al = getF(b, p, e, 0, 4) + 5 + if al > maxAL then + return nil, "FSE accuracy log too large" + end + local bp = 4 + local remaining = lshift(1, al) + 1 + local threshold = lshift(1, al) + local nbBits = al + 1 + local sym = 0 + local prev0 = false + while remaining > 1 and sym <= maxSym do + if prev0 then + local n0 = sym + while true do + local v = getF(b, p, e, bp, 2) + bp += 2 + if v == 3 then + n0 += 3 + if n0 > maxSym or bp > (e - p) * 8 then + return nil, "bad FSE table" + end + else + n0 += v + break + end + end + if n0 > maxSym then + return nil, "bad FSE table" + end + while sym < n0 do + norm[sym + 1] = 0 + sym += 1 + end + end + local max = 2 * threshold - 1 - remaining + local count + local low = getF(b, p, e, bp, nbBits - 1) + if low < max then + count = low + bp += nbBits - 1 + else + count = getF(b, p, e, bp, nbBits) + if count >= threshold then + count -= max + end + bp += nbBits + end + count -= 1 + remaining -= if count < 0 then -count else count + if remaining < 1 then + return nil, "bad FSE table" + end + norm[sym + 1] = count + sym += 1 + prev0 = count == 0 + while remaining < threshold do + nbBits -= 1 + threshold = rshift(threshold, 1) + end + end + if remaining ~= 1 then + return nil, "bad FSE table" + end + local used = rshift(bp + 7, 3) + if p + used > e then + return nil, "truncated FSE table" + end + for s = sym, maxSym do + norm[s + 1] = 0 + end + return al, used, sym +end + +local function predefined(dist: { number }, al: number): buffer + local t = bcreate(lshift(1, al) * 4) + buildFse(dist, #dist, al, t) + return t +end +local LL_PRE, ML_PRE, OF_PRE = predefined(LL_DEFAULT, 6), predefined(ML_DEFAULT, 6), predefined(OF_DEFAULT, 5) + +-- ------------------------------------------------------------------------------------------------ Huffman +-- hufTable(b, p, e, st) -> bytesUsed | nil, message: a Huffman tree description into st.huf (u16: sym | nbBits << 8) +local weights = bcreate(256) +local wfse = bcreate(64 * 4) +local function hufTable(b: buffer, p: number, e: number, st: any): (number?, string?) + if p >= e then + return nil, "truncated Huffman table" + end + local hdr = readu8(b, p) + local n = 0 + local used + if hdr >= 128 then + n = hdr - 127 + used = 1 + rshift(n + 1, 1) + if p + used > e then + return nil, "truncated Huffman table" + end + for i = 0, n - 1 do + local byte = readu8(b, p + 1 + rshift(i, 1)) + writeu8(weights, i, if band(i, 1) == 0 then rshift(byte, 4) else band(byte, 15)) + end + else + used = 1 + hdr + if p + used > e then + return nil, "truncated Huffman table" + end + local q, qe = p + 1, p + 1 + hdr + local norm = st.norm + local al, nb = ncount(b, q, qe, 255, 6, norm) + if not al then + return nil, nb + end + local ok, msg = buildFse(norm, 256, al, wfse) + if not ok then + return nil, msg + end + local ss = q + nb + local off = streamBits(b, ss, qe) + if off < 0 then + return nil, "bad Huffman weight stream" + end + local s1 = peek(b, ss, off, al) + off -= al + local s2 = peek(b, ss, off, al) + off -= al + while true do + if n > 254 then + return nil, "too many Huffman weights" + end + local e1 = readu32(wfse, s1 * 4) + writeu8(weights, n, band(e1, 255)) + n += 1 + local k = band(rshift(e1, 8), 255) + s1 = rshift(e1, 16) + peek(b, ss, off, k) + off -= k + if off < 0 then + writeu8(weights, n, band(readu32(wfse, s2 * 4), 255)) + n += 1 + break + end + local e2 = readu32(wfse, s2 * 4) + writeu8(weights, n, band(e2, 255)) + n += 1 + k = band(rshift(e2, 8), 255) + s2 = rshift(e2, 16) + peek(b, ss, off, k) + off -= k + if off < 0 then + writeu8(weights, n, band(readu32(wfse, s1 * 4), 255)) + n += 1 + break + end + end + end + -- the last weight is implied: the total must reach the next power of two + local total = 0 + for i = 0, n - 1 do + local w = readu8(weights, i) + if w > 11 then + return nil, "bad Huffman weight" + end + if w > 0 then + total += lshift(1, w - 1) + end + end + if total == 0 or total >= 2048 then + return nil, "bad Huffman weights" + end + local maxBits = HB[total] + 1 + local rest = lshift(1, maxBits) - total + if band(rest, rest - 1) ~= 0 then + return nil, "bad Huffman weights" + end + writeu8(weights, n, HB[rest] + 1) + local nsym = n + 1 + -- codes: the longest first, in symbol order within a length + local rankCount = table.create(13, 0) + for i = 0, nsym - 1 do + local w = readu8(weights, i) + if w > 0 then + local bits = maxBits + 1 - w + rankCount[bits + 1] += 1 + end + end + local rankIdx = table.create(13, 0) + rankIdx[maxBits + 1] = 0 + for i = maxBits, 1, -1 do + rankIdx[i] = rankIdx[i + 1] + rankCount[i + 1] * lshift(1, maxBits - i) + end + if rankIdx[1] ~= lshift(1, maxBits) then + return nil, "bad Huffman weights" + end + local t = st.huf + for i = 0, nsym - 1 do + local w = readu8(weights, i) + if w > 0 then + local bits = maxBits + 1 - w + local code = rankIdx[bits + 1] + local len = lshift(1, maxBits - bits) + local v = i + bits * 256 + for k = code, code + len - 1 do + writeu16(t, k * 2, v) + end + rankIdx[bits + 1] = code + len + end + end + st.hufBits = maxBits + return used, nil +end + +-- one Huffman stream [s, e) -> cnt literals at lit[dp] | nil, message +local function hufStream(b: buffer, s: number, e: number, t: buffer, mb: number, lit: buffer, dp: number, cnt: number): string? + local off = streamBits(b, s, e) + if off < 0 then + return "bad Huffman stream" + end + local mmask = lshift(1, mb) - 1 + local fastEnd = blen(b) - 4 + for k = dp, dp + cnt - 1 do + local lo = off - mb + local idx + if lo >= 0 then + local byte = s + rshift(lo, 3) + if byte <= fastEnd then + idx = band(rshift(readu32(b, byte), band(lo, 7)), mmask) + else + idx = peek(b, s, off, mb) + end + else + idx = peek(b, s, off, mb) + end + local v = readu16(t, idx * 2) + writeu8(lit, k, v) + off -= rshift(v, 8) + end + if off ~= 0 then + return "Huffman stream size mismatch" + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ frames +-- grow st.out to hold need bytes (doubling, capped at st.maxBytes): true | false (over the limit) +local function grow(st: any, need: number): boolean + if need > st.maxBytes then + return false + end + local cap = math.min(st.maxBytes, math.max(blen(st.out) * 2, need, 65536)) + local nb = bcreate(cap) + bcopy(nb, 0, st.out, 0, st.op) + st.out = nb + return true +end + +-- a compressed block [p, e): nil (ok) | code, message +local function block(b: buffer, p: number, e: number, st: any): (string?, string?) + -- literals section + local b0 = readu8(b, p) + local ltype = band(b0, 3) + local sf = band(rshift(b0, 2), 3) + local regen + local litSrc, litPos + local lit = st.lit + if ltype <= 1 then + if sf == 0 or sf == 2 then + regen = rshift(b0, 3) + p += 1 + elseif sf == 1 then + if p + 2 > e then + return "TRUNCATED", "truncated literals header" + end + regen = rshift(b0, 4) + readu8(b, p + 1) * 16 + p += 2 + else + if p + 3 > e then + return "TRUNCATED", "truncated literals header" + end + regen = rshift(b0, 4) + readu8(b, p + 1) * 16 + readu8(b, p + 2) * 4096 + p += 3 + end + if regen > BLOCK_MAX then + return "CORRUPT", "literals too large" + end + if ltype == 0 then + if p + regen > e then + return "TRUNCATED", "truncated raw literals" + end + litSrc, litPos = b, p + p += regen + else + if p + 1 > e then + return "TRUNCATED", "truncated RLE literals" + end + bfill(lit, 0, readu8(b, p), regen) + litSrc, litPos = lit, 0 + p += 1 + end + else + local csize + if sf <= 1 then + if p + 3 > e then + return "TRUNCATED", "truncated literals header" + end + local v = b0 + readu8(b, p + 1) * 256 + readu8(b, p + 2) * 65536 + regen = band(rshift(v, 4), 0x3FF) + csize = band(rshift(v, 14), 0x3FF) + p += 3 + elseif sf == 2 then + if p + 4 > e then + return "TRUNCATED", "truncated literals header" + end + local v = readu32(b, p) + regen = band(rshift(v, 4), 0x3FFF) + csize = rshift(v, 18) + p += 4 + else + if p + 5 > e then + return "TRUNCATED", "truncated literals header" + end + local v = readu32(b, p) + regen = band(rshift(v, 4), 0x3FFFF) + csize = rshift(v, 22) + readu8(b, p + 4) * 1024 + p += 5 + end + if regen > BLOCK_MAX then + return "CORRUPT", "literals too large" + end + if p + csize > e then + return "TRUNCATED", "truncated compressed literals" + end + local hs, he = p, p + csize + p = he + if ltype == 2 then + local used, herr = hufTable(b, hs, he, st) + if not used then + return "CORRUPT", herr + end + hs += used + elseif not st.hufBits then + return "CORRUPT", "treeless literals without a previous Huffman table" + end + local t, mb = st.huf, st.hufBits + if sf == 0 then + local herr = hufStream(b, hs, he, t, mb, lit, 0, regen) + if herr then + return "CORRUPT", herr + end + else + if hs + 6 > he then + return "CORRUPT", "truncated jump table" + end + local l1, l2, l3 = readu16(b, hs), readu16(b, hs + 2), readu16(b, hs + 4) + local s1 = hs + 6 + local s2 = s1 + l1 + local s3 = s2 + l2 + local s4 = s3 + l3 + if s4 > he then + return "CORRUPT", "bad jump table" + end + local seg = rshift(regen + 3, 2) + local last = regen - 3 * seg + if last < 0 then + return "CORRUPT", "bad 4-stream literals size" + end + local herr = hufStream(b, s1, s2, t, mb, lit, 0, seg) + or hufStream(b, s2, s3, t, mb, lit, seg, seg) + or hufStream(b, s3, s4, t, mb, lit, 2 * seg, seg) + or hufStream(b, s4, he, t, mb, lit, 3 * seg, last) + if herr then + return "CORRUPT", herr + end + end + litSrc, litPos = lit, 0 + end + + -- sequences section header + if p >= e then + return "TRUNCATED", "missing sequences header" + end + local nbSeq = readu8(b, p) + p += 1 + if nbSeq >= 128 then + if nbSeq == 255 then + if p + 2 > e then + return "TRUNCATED", "truncated sequences header" + end + nbSeq = readu16(b, p) + 0x7F00 + p += 2 + else + if p + 1 > e then + return "TRUNCATED", "truncated sequences header" + end + nbSeq = (nbSeq - 128) * 256 + readu8(b, p) + p += 1 + end + end + local op = st.op + if nbSeq == 0 then + if p ~= e then + return "CORRUPT", "data after an empty sequences section" + end + if op + regen > blen(st.out) then + if not grow(st, op + regen) then + return "LIMIT", "output over the size limit" + end + end + bcopy(st.out, op, litSrc, litPos, regen) + st.op = op + regen + return nil, nil + end + if p >= e then + return "TRUNCATED", "missing compression modes" + end + local modes = readu8(b, p) + p += 1 + if band(modes, 3) ~= 0 then + return "CORRUPT", "reserved bits set in compression modes" + end + -- the three tables, in the order LL, OF, ML + local tabs = st.tabs + for k = 1, 3 do + local mode = band(rshift(modes, 8 - 2 * k), 3) + local maxSym = if k == 1 then 35 elseif k == 2 then 31 else 52 + local maxAL = if k == 1 then 9 elseif k == 2 then 8 else 9 + if mode == 0 then + tabs[k] = if k == 1 then LL_PRE elseif k == 2 then OF_PRE else ML_PRE + tabs[k + 3] = if k == 2 then 5 else 6 + elseif mode == 1 then + if p >= e then + return "TRUNCATED", "truncated RLE table" + end + local sym = readu8(b, p) + p += 1 + if sym > maxSym then + return "CORRUPT", "bad RLE symbol" + end + local t = st.rle[k] + writeu32(t, 0, sym) + tabs[k] = t + tabs[k + 3] = 0 + elseif mode == 2 then + local norm = st.norm + local al, used, nsym = ncount(b, p, e, maxSym, maxAL, norm) + if not al then + return "CORRUPT", used + end + p += used + local t = st.dyn[k] + local ok, msg = buildFse(norm, nsym :: number, al, t) + if not ok then + return "CORRUPT", msg + end + tabs[k] = t + tabs[k + 3] = al + else + if not tabs[k] then + return "CORRUPT", "repeated table without a previous one" + end + end + end + local llT, ofT, mlT = tabs[1] :: buffer, tabs[2] :: buffer, tabs[3] :: buffer + local llAL, ofAL, mlAL = tabs[4] :: number, tabs[5] :: number, tabs[6] :: number + + -- the sequences bitstream + local s = p + local off = streamBits(b, s, e) + if off < 0 then + return "CORRUPT", "bad sequences bitstream" + end + local llS = peek(b, s, off, llAL) + off -= llAL + local ofS = peek(b, s, off, ofAL) + off -= ofAL + local mlS = peek(b, s, off, mlAL) + off -= mlAL + local rep1, rep2, rep3 = st.rep1, st.rep2, st.rep3 + local out = st.out + local cap = blen(out) + local frameStart = st.frameStart + local lp, litEnd = litPos, litPos + regen + local fastEnd = blen(b) - 4 + for i = 1, nbSeq do + local ofE, llE, mlE = readu32(ofT, ofS * 4), readu32(llT, llS * 4), readu32(mlT, mlS * 4) + local ofCode = band(ofE, 255) + local mlCode = band(mlE, 255) + 1 + local llCode = band(llE, 255) + 1 + -- offset bits, then match length bits, then literal length bits + local ofv + if ofCode > 24 then + local hiN = ofCode - 24 + local hi = peek(b, s, off, hiN) + off -= hiN + ofv = lshift(1, ofCode) + hi * 16777216 + peek(b, s, off, 24) + off -= 24 + elseif ofCode > 0 then + local lo = off - ofCode + local v + if lo >= 0 and s + rshift(lo, 3) <= fastEnd then + v = band(rshift(readu32(b, s + rshift(lo, 3)), band(lo, 7)), lshift(1, ofCode) - 1) + else + v = peek(b, s, off, ofCode) + end + off = lo + ofv = lshift(1, ofCode) + v + else + ofv = 1 + end + local ml = ML_BASE[mlCode] + local nb = ML_BITS[mlCode] + if nb > 0 then + ml += peek(b, s, off, nb) + off -= nb + end + local ll = LL_BASE[llCode] + nb = LL_BITS[llCode] + if nb > 0 then + ll += peek(b, s, off, nb) + off -= nb + end + -- repeat offsets + local offset + if ofv > 3 then + offset = ofv - 3 + rep3 = rep2 + rep2 = rep1 + rep1 = offset + else + local idx = ofv - 1 + if ll == 0 then + idx += 1 + end + if idx == 0 then + offset = rep1 + else + if idx == 1 then + offset = rep2 + elseif idx == 2 then + offset = rep3 + else + offset = rep1 - 1 + end + if idx > 1 then + rep3 = rep2 + end + rep2 = rep1 + rep1 = offset + end + end + -- state updates (not after the last sequence): LL, ML, OF + if i < nbSeq then + nb = band(rshift(llE, 8), 255) + llS = rshift(llE, 16) + peek(b, s, off, nb) + off -= nb + nb = band(rshift(mlE, 8), 255) + mlS = rshift(mlE, 16) + peek(b, s, off, nb) + off -= nb + nb = band(rshift(ofE, 8), 255) + ofS = rshift(ofE, 16) + peek(b, s, off, nb) + off -= nb + end + -- execute + if lp + ll > litEnd then + return "CORRUPT", "literal length past the literals" + end + local need = op + ll + ml + if need > cap then + st.op = op + if not grow(st, need) then + return "LIMIT", "output over the size limit" + end + out = st.out + cap = blen(out) + end + if ll > 0 then + bcopy(out, op, litSrc, lp, ll) + op += ll + lp += ll + end + if offset > op - frameStart or offset < 1 then + return "CORRUPT", "match offset before the frame start" + end + local from = op - offset + if offset >= ml then + bcopy(out, op, out, from, ml) + op += ml + elseif offset == 1 then + bfill(out, op, readu8(out, from), ml) + op += ml + else + -- overlapping: copy in chunks of `offset` bytes (each chunk's source precedes its destination) + local left = ml + while left > 0 do + local n = if left < offset then left else offset + bcopy(out, op, out, from, n) + op += n + from += n + left -= n + end + end + end + if off ~= 0 then + return "CORRUPT", "sequences bitstream size mismatch" + end + local rest = litEnd - lp + if rest > 0 then + if op + rest > cap then + st.op = op + if not grow(st, op + rest) then + return "LIMIT", "output over the size limit" + end + out = st.out + end + bcopy(out, op, litSrc, lp, rest) + op += rest + end + st.op = op + st.rep1, st.rep2, st.rep3 = rep1, rep2, rep3 + return nil, nil +end + +-- decompress(b, start, stop, maxBytes, verify) -> out, length, consumedEnd | nil, code, message, offset +function Decode.decompress(b: buffer, start: number, stop: number, maxBytes: number, verify: boolean): (buffer?, any, any, any) + local st: any = { + out = bcreate(math.min(maxBytes, math.max(4096, (stop - start) * 3))), + op = 0, + maxBytes = maxBytes, + lit = bcreate(BLOCK_MAX + 64), + huf = bcreate(2048 * 2), + hufBits = nil, + norm = table.create(256, 0), + tabs = {}, + rle = { bcreate(4), bcreate(4), bcreate(4) }, + dyn = { bcreate(512 * 4), bcreate(256 * 4), bcreate(512 * 4) }, + frameStart = 0, + rep1 = 1, + rep2 = 4, + rep3 = 8, + } + local pos = start + local frames = 0 + if stop - start < 4 then + return nil, "TRUNCATED", "not a zstd stream (too short)", start + end + while pos < stop do + if pos + 4 > stop then + return nil, "TRUNCATED", "truncated frame magic", pos + end + local magic = readu32(b, pos) + if band(magic, 0xFFFFFFF0) == 0x184D2A50 then + if pos + 8 > stop then + return nil, "TRUNCATED", "truncated skippable frame", pos + end + local size = readu32(b, pos + 4) + if pos + 8 + size > stop then + return nil, "TRUNCATED", "truncated skippable frame", pos + end + pos += 8 + size + frames += 1 + continue + end + if magic ~= MAGIC then + return nil, "CORRUPT", if frames == 0 then "bad magic" else "unknown data after frame " .. frames, pos + end + pos += 4 + if pos + 1 > stop then + return nil, "TRUNCATED", "truncated frame header", pos + end + local fhd = readu8(b, pos) + pos += 1 + local fcsFlag = rshift(fhd, 6) + local single = band(fhd, 0x20) ~= 0 + if band(fhd, 8) ~= 0 then + return nil, "CORRUPT", "reserved frame header bit set", pos - 1 + end + local checksum = band(fhd, 4) ~= 0 + local didFlag = band(fhd, 3) + local didSize = if didFlag == 3 then 4 else didFlag + local fcsSize = if fcsFlag == 0 then (if single then 1 else 0) else lshift(1, fcsFlag) + local hsize = (if single then 0 else 1) + didSize + fcsSize + if pos + hsize > stop then + return nil, "TRUNCATED", "truncated frame header", pos + end + local windowSize = 0 + if not single then + local wd = readu8(b, pos) + pos += 1 + local wlog = 10 + rshift(wd, 3) + if wlog > 41 then + return nil, "CORRUPT", "bad window size", pos - 1 + end + local base = 2 ^ wlog + windowSize = base + base / 8 * band(wd, 7) + end + local did = 0 + if didSize == 1 then + did = readu8(b, pos) + elseif didSize == 2 then + did = readu16(b, pos) + elseif didSize == 4 then + did = readu32(b, pos) + end + pos += didSize + if did ~= 0 then + return nil, "UNSUPPORTED", "dictionaries are not supported (dictionary " .. did .. ")", pos - didSize + end + local fcs = -1 + if fcsSize == 1 then + fcs = readu8(b, pos) + elseif fcsSize == 2 then + fcs = readu16(b, pos) + 256 + elseif fcsSize == 4 then + fcs = readu32(b, pos) + elseif fcsSize == 8 then + fcs = readu32(b, pos) + readu32(b, pos + 4) * 4294967296 + end + pos += fcsSize + if single then + windowSize = fcs + end + local blockMax = math.min(windowSize, BLOCK_MAX) + local frameStart = st.op + if fcs >= 0 then + if frameStart + fcs > st.maxBytes then + return nil, "LIMIT", string.format("frame content size %d is over the %d byte limit", fcs, st.maxBytes), pos + end + if frameStart + fcs > blen(st.out) then + grow(st, frameStart + fcs) + end + end + st.frameStart = frameStart + st.rep1, st.rep2, st.rep3 = 1, 4, 8 + st.hufBits = nil + table.clear(st.tabs) + -- blocks + local last = false + repeat + if pos + 3 > stop then + return nil, "TRUNCATED", "truncated block header", pos + end + local bh = readu16(b, pos) + readu8(b, pos + 2) * 65536 + last = band(bh, 1) ~= 0 + local btype = band(rshift(bh, 1), 3) + local bsize = rshift(bh, 3) + pos += 3 + if bsize > blockMax then + return nil, "CORRUPT", "block larger than the maximum block size", pos - 3 + end + if btype == 0 then + if pos + bsize > stop then + return nil, "TRUNCATED", "truncated raw block", pos + end + if st.op + bsize > blen(st.out) and not grow(st, st.op + bsize) then + return nil, "LIMIT", "output over the size limit", pos + end + bcopy(st.out, st.op, b, pos, bsize) + st.op += bsize + pos += bsize + elseif btype == 1 then + if pos + 1 > stop then + return nil, "TRUNCATED", "truncated RLE block", pos + end + if st.op + bsize > blen(st.out) and not grow(st, st.op + bsize) then + return nil, "LIMIT", "output over the size limit", pos + end + bfill(st.out, st.op, readu8(b, pos), bsize) + st.op += bsize + pos += 1 + elseif btype == 2 then + if pos + bsize > stop then + return nil, "TRUNCATED", "truncated compressed block", pos + end + if bsize == 0 then + return nil, "CORRUPT", "empty compressed block", pos + end + local code, msg = block(b, pos, pos + bsize, st) + if code then + return nil, code, msg, pos + end + pos += bsize + else + return nil, "CORRUPT", "reserved block type", pos - 3 + end + until last + local size = st.op - frameStart + if fcs >= 0 and size ~= fcs then + return nil, "CORRUPT", string.format("frame decoded to %d bytes, header says %d", size, fcs), pos + end + if checksum then + if pos + 4 > stop then + return nil, "TRUNCATED", "missing content checksum", pos + end + if verify then + local _, lo = Xxh64.hash(st.out, frameStart, size) + local want = readu32(b, pos) + if lo ~= want then + return nil, "CHECKSUM", string.format("content checksum mismatch (%08x, expected %08x)", lo, want), pos + end + end + pos += 4 + end + frames += 1 + end + return st.out, st.op, pos +end + +Decode.hash = Xxh64.hash + +return Decode diff --git a/src/Formats/codecs/Zstd/Xxh64.luau b/src/Formats/codecs/Zstd/Xxh64.luau new file mode 100644 index 0000000..5aa48e8 --- /dev/null +++ b/src/Formats/codecs/Zstd/Xxh64.luau @@ -0,0 +1,155 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Zstd/Xxh64: XXH64 (seed 0) of a buffer range, computed on 32-bit halves held in doubles (Luau and LuaJIT have +-- no 64-bit integers). 64 x 64 -> 64 products split the low operand into 16-bit limbs so every partial product is +-- exact below 2^53. From the xxHash specification (Yann Collet, BSD-2); no code copied. zstd stores the low 32 bits +-- of the hash as the frame content checksum. Never throws (the caller passes an in-range buffer slice). +local bor, bxor, lshift, rshift = bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift +local readu8, readu32 = buffer.readu8, buffer.readu32 + +local T32 = 4294967296 + +local P1H, P1L = 0x9E3779B1, 0x85EBCA87 +local P2H, P2L = 0xC2B2AE3D, 0x27D4EB4F +local P3H, P3L = 0x165667B1, 0x9E3779F9 +local P4H, P4L = 0x85EBCA77, 0xC2B2AE63 +local P5H, P5L = 0x27D4EB2F, 0x165667C5 + +-- (ah, al) * (bh, bl) mod 2^64 +local function mul(ah: number, al: number, bh: number, bl: number): (number, number) + local a0 = al % 65536 + local a1 = (al - a0) / 65536 + local b0 = bl % 65536 + local b1 = (bl - b0) / 65536 + local mid = a1 * b0 + a0 * b1 + local mid0 = mid % 65536 + local lo = a0 * b0 + mid0 * 65536 + local lo32 = lo % T32 + local hi = a1 * b1 + (mid - mid0) / 65536 + (lo - lo32) / T32 + hi += (a0 * bh + ((a1 * bh) % 65536) * 65536) + (b0 * ah + ((b1 * ah) % 65536) * 65536) + return hi % T32, lo32 +end + +local function add(ah: number, al: number, bh: number, bl: number): (number, number) + local l = al + bl + local h = ah + bh + if l >= T32 then + l -= T32 + h += 1 + end + return h % T32, l +end + +-- rotl by r in 1..31 +local function rotl(h: number, l: number, r: number): (number, number) + return bor(lshift(h, r), rshift(l, 32 - r)), bor(lshift(l, r), rshift(h, 32 - r)) +end + +local P1L0, P1L1 = P1L % 65536, P1L // 65536 +local P2L0, P2L1 = P2L % 65536, P2L // 65536 + +-- acc = rotl(acc + input * P2, 31) * P1, with both products written out (the hot path: 4 per 32 input bytes) +local function round(ah: number, al: number, ih: number, il: number): (number, number) + local a0 = il % 65536 + local a1 = (il - a0) / 65536 + local mid = a1 * P2L0 + a0 * P2L1 + local mid0 = mid % 65536 + local lo = a0 * P2L0 + mid0 * 65536 + local ml = lo % T32 + local mh = a1 * P2L1 + (mid - mid0) / 65536 + (lo - ml) / T32 + a0 * P2H + ((a1 * P2H) % 65536) * 65536 + P2L0 * ih + ((P2L1 * ih) % 65536) * 65536 + local l = al + ml + local h = ah + mh + if l >= T32 then + l -= T32 + h += 1 + end + h %= T32 + -- rotl 31 = rotr 1, in arithmetic (cheaper than bit32 calls on LuaJIT) + local hb, lb = h % 2, l % 2 + local rh, rl = hb * 2147483648 + (l - lb) / 2, lb * 2147483648 + (h - hb) / 2 + a0 = rl % 65536 + a1 = (rl - a0) / 65536 + mid = a1 * P1L0 + a0 * P1L1 + mid0 = mid % 65536 + lo = a0 * P1L0 + mid0 * 65536 + ml = lo % T32 + mh = a1 * P1L1 + (mid - mid0) / 65536 + (lo - ml) / T32 + a0 * P1H + ((a1 * P1H) % 65536) * 65536 + P1L0 * rh + ((P1L1 * rh) % 65536) * 65536 + return mh % T32, ml +end + +local function merge(hh: number, hl: number, vh: number, vl: number): (number, number) + local rh, rl = round(0, 0, vh, vl) + hh, hl = bxor(hh, rh), bxor(hl, rl) + hh, hl = mul(hh, hl, P1H, P1L) + return add(hh, hl, P4H, P4L) +end + +local Xxh64 = {} + +-- hash(b, offset, length) -> hi, lo (the 64-bit hash as two unsigned 32-bit halves) +function Xxh64.hash(b: buffer, offset: number, length: number): (number, number) + local p = offset + local e = offset + length + local hh, hl = 0, 0 + if length >= 32 then + local v1h, v1l = add(P1H, P1L, P2H, P2L) + local v2h, v2l = P2H, P2L + local v3h, v3l = 0, 0 + local v4h, v4l = add(0, 0, (T32 - P1H - 1) % T32, (T32 - P1L) % T32) -- -P1 (two's complement) + local limit = e - 32 + while p <= limit do + v1h, v1l = round(v1h, v1l, readu32(b, p + 4), readu32(b, p)) + v2h, v2l = round(v2h, v2l, readu32(b, p + 12), readu32(b, p + 8)) + v3h, v3l = round(v3h, v3l, readu32(b, p + 20), readu32(b, p + 16)) + v4h, v4l = round(v4h, v4l, readu32(b, p + 28), readu32(b, p + 24)) + p += 32 + end + local ah, al = rotl(v1h, v1l, 1) + local bh, bl = rotl(v2h, v2l, 7) + hh, hl = add(ah, al, bh, bl) + bh, bl = rotl(v3h, v3l, 12) + hh, hl = add(hh, hl, bh, bl) + bh, bl = rotl(v4h, v4l, 18) + hh, hl = add(hh, hl, bh, bl) + hh, hl = merge(hh, hl, v1h, v1l) + hh, hl = merge(hh, hl, v2h, v2l) + hh, hl = merge(hh, hl, v3h, v3l) + hh, hl = merge(hh, hl, v4h, v4l) + else + hh, hl = P5H, P5L + end + hh, hl = add(hh, hl, math.floor(length / T32) % T32, length % T32) + while p + 8 <= e do + local kh, kl = round(0, 0, readu32(b, p + 4), readu32(b, p)) + hh, hl = bxor(hh, kh), bxor(hl, kl) + hh, hl = rotl(hh, hl, 27) + hh, hl = mul(hh, hl, P1H, P1L) + hh, hl = add(hh, hl, P4H, P4L) + p += 8 + end + if p + 4 <= e then + local kh, kl = mul(0, readu32(b, p), P1H, P1L) + hh, hl = bxor(hh, kh), bxor(hl, kl) + hh, hl = rotl(hh, hl, 23) + hh, hl = mul(hh, hl, P2H, P2L) + hh, hl = add(hh, hl, P3H, P3L) + p += 4 + end + while p < e do + local kh, kl = mul(0, readu8(b, p), P5H, P5L) + hh, hl = bxor(hh, kh), bxor(hl, kl) + hh, hl = rotl(hh, hl, 11) + hh, hl = mul(hh, hl, P1H, P1L) + p += 1 + end + -- avalanche + hl = bxor(hl, rshift(hh, 1)) -- h ^= h >> 33 + hh, hl = mul(hh, hl, P2H, P2L) + hh, hl = bxor(hh, rshift(hh, 29)), bxor(hl, bor(rshift(hl, 29), lshift(hh, 3))) -- h ^= h >> 29 + hh, hl = mul(hh, hl, P3H, P3L) + hl = bxor(hl, hh) -- h ^= h >> 32 + return hh, hl +end + +return Xxh64 diff --git a/src/Formats/codecs/Zstd/init.luau b/src/Formats/codecs/Zstd/init.luau new file mode 100644 index 0000000..c48de03 --- /dev/null +++ b/src/Formats/codecs/Zstd/init.luau @@ -0,0 +1,89 @@ +--!strict +-- codecs/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd +-- data build on it. Written from the specification. Supports every frame feature a dictionary-less stream uses: +-- concatenated and skippable frames, raw / RLE / compressed blocks, Huffman literals (1 / 4 streams, repeated tables), +-- predefined / RLE / compressed / repeated FSE tables, repeat offsets, the XXH64 content checksum (verified). +-- Not supported: dictionaries (Err.UNSUPPORTED), compression. +-- +-- local Zstd = require("@formats/codecs/Zstd") +-- local out, err = Zstd.decompress(buf) -- -> buffer, consumedEnd | nil, Err +-- local out, err = Zstd.decompress(buf, off, len, { maxBytes = 2^24, verify = false }) +-- +-- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / UNSUPPORTED / LIMIT / ARG). +local Err = require("@formats/core/Err") +local Decode = require("@formats/codecs/Zstd/Decode") + +local Zstd = {} + +export type Options = { + maxBytes: number?, -- refuse output larger than this (default 2^30) + verify: boolean?, -- check the content checksum when a frame has one (default true) +} + +local CODES: { [string]: string } = { + TRUNCATED = Err.TRUNCATED, + CORRUPT = Err.CORRUPT, + CHECKSUM = Err.CHECKSUM, + UNSUPPORTED = Err.UNSUPPORTED, + LIMIT = Err.LIMIT, +} + +-- magic numbers: a zstd frame, and skippable frames (0x184D2A50 .. 0x184D2A5F) +Zstd.MAGIC = "\40\181\47\253" + +-- isFrame(buf, offset?) -> true when a zstd (or skippable) frame starts there +function Zstd.isFrame(buf: buffer, offset: number?): boolean + local o = offset or 0 + if type(buf) ~= "buffer" or o < 0 or o + 4 > buffer.len(buf) then + return false + end + local m = buffer.readu32(buf, o) + return m == 0xFD2FB528 or bit32.band(m, 0xFFFFFFF0) == 0x184D2A50 +end + +-- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err. Every frame in the range is decoded +-- and the outputs concatenated; data after the last frame that is not a frame is an error (as zstd -d does). +function Zstd.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) + local b: buffer + if type(buf) == "string" then + b = buffer.fromstring(buf) + elseif type(buf) == "buffer" then + b = buf + else + return nil, Err.new(Err.ARG, "Zstd.decompress: expected a buffer or a string, got " .. typeof(buf)) + end + local n = buffer.len(b) + local o = offset or 0 + if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then + return nil, Err.new(Err.ARG, "Zstd.decompress: bad offset " .. tostring(offset)) + end + local l = length or (n - o) + if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then + return nil, Err.new(Err.ARG, "Zstd.decompress: bad length " .. tostring(length)) + end + l = math.min(l, n - o) + local maxBytes = if opts and opts.maxBytes ~= nil then opts.maxBytes else 2 ^ 30 + if type(maxBytes) ~= "number" or maxBytes < 0 then + return nil, Err.new(Err.ARG, "Zstd.decompress: bad maxBytes " .. tostring(maxBytes)) + end + local verify = not (opts and opts.verify == false) + local out, len, consumed, at = Decode.decompress(b, o, o + l, maxBytes, verify) + if not out then + return nil, Err.new(CODES[len] or Err.CORRUPT, tostring(consumed), at) + end + if buffer.len(out) ~= len then + local r = buffer.create(len) + buffer.copy(r, 0, out, 0, len) + out = r + end + return out, consumed +end + +-- xxh64(buf, offset?, length?) -> hi, lo: the XXH64 hash (seed 0) as two unsigned 32-bit halves +function Zstd.xxh64(buf: buffer, offset: number?, length: number?): (number, number) + local o = math.clamp(offset or 0, 0, buffer.len(buf)) + local l = math.clamp(length or (buffer.len(buf) - o), 0, buffer.len(buf) - o) + return Decode.hash(buf, o, l) +end + +return Zstd diff --git a/tests/archive/zst.luau b/tests/archive/zst.luau new file mode 100644 index 0000000..4908393 --- /dev/null +++ b/tests/archive/zst.luau @@ -0,0 +1,90 @@ +-- archive/zst tests: the contract, sniff (zstd and skippable-frame magic), decode of zstd CLI output into a one-entry +-- single-stream archive (entry name from opts.name, size, read), F.load detection by content, read-only errors, and +-- the fuzz no-throw pass. Fixtures: tools/fixtures/zstd.py (shared with tests/codecs/zstd.luau). +local T = require("@tests/T") +local F = require("@formats") +local Zst = require("@formats/archive/zst") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/zstd") + +local t = T.suite("zst") + +-- contract +t:eq(Zst.name, "zst", "name") +t:eq(Zst.category, "archive", "category") +t:check(Zst.caps.decode and not Zst.caps.encode, "caps") + +local function case(name: string): any + for _, c in Fx.cases do + if c.name == name then + return c + end + end + error("no case " .. name) +end + +-- sniff +t:eq(Zst.sniff(Bytes.reader(buffer.fromstring(case("text/l3").data))), 1, "sniff zstd") +t:eq(Zst.sniff(Bytes.reader(buffer.fromstring(case("skipfirst/frames").data))), 0.5, "sniff skippable frame") +t:eq(Zst.sniff(Bytes.reader(buffer.fromstring("PK\3\4"))), 0, "sniff other") +t:eq(Zst.sniff(Bytes.reader(buffer.create(0))), 0, "sniff empty") + +-- decode: one entry, named after the file +for _, name in { "text/l3", "runs/ultra22", "multi/frames", "empty/l3", "big/l19" } do + local c = case(name) + local a, err = Zst.decode(Bytes.reader(buffer.fromstring(c.data)), { name = "dir/notes.txt.zst" }) + t:check(a, name .. ": " .. tostring(err)) + local list = a:list() + t:eq(#list, 1, name .. ": one entry") + t:eq(list[1].name, "notes.txt", name .. ": entry name") + t:eq(list[1].size, #Fx.corpora[c.corpus], name .. ": size") + t:eq(list[1].compressedSize, #c.data, name .. ": compressedSize") + t:check(a.meta.stream == true and a.kind == "archive" and a.format == "zst", name .. ": archive fields") + local data = a:read(list[1].name) + t:check(data and buffer.tostring(data) == Fx.corpora[c.corpus], name .. ": read") +end +do + local c = case("short/l3") + local a = Zst.decode(Bytes.reader(buffer.fromstring(c.data))) :: any + t:eq(a:list()[1].name, "data", "no name -> data") + local a2 = Zst.decode(Bytes.reader(buffer.fromstring(c.data)), { name = "backup.tzst" }) :: any + t:eq(a2:list()[1].name, "backup.tar", ".tzst -> .tar") + local _, e = a:read("nope") + t:check(e and e.code == Err.ARG, "missing entry") + local _, we = a:write() + t:check(we and we.code == Err.UNSUPPORTED, "read-only: " .. tostring(we)) + -- inside a bigger buffer (the reader's range) + local big = buffer.create(#c.data + 10) + buffer.writestring(big, 5, c.data) + local a3 = Zst.decode(Bytes.reader(big, 5, #c.data)) :: any + t:check(a3 and buffer.tostring(a3:read("data")) == Fx.corpora.short, "reader range") +end + +-- the api: detection by content, the name from opts +do + local c = case("text/l5") + local a, err = F.load(c.data, { name = "x/readme.md.zst" }) + t:check(a and a.format == "zst", "F.load detects zst: " .. tostring(err)) + t:eq(a:list()[1].name, "readme.md", "F.load entry name") + t:eq(F.detect(c.data), "zst", "F.detect") + local _, e = F.load(string.sub(c.data, 1, 30), { format = "zst" }) + t:check(e and e.code == Err.TRUNCATED, "truncated through the api: " .. tostring(e)) + local _, se = F.save(a, nil, { format = "zst" }) + t:check(se and se.code == Err.UNSUPPORTED, "no encoder") +end + +-- fuzz +do + local samples = {} + for i, c in Fx.cases do + if i % 11 == 0 and #c.data < 30000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + return Zst.decode(Bytes.reader(b), { maxBytes = 1e6 }) + end, samples, { mutations = 10, garbage = 500 }) +end + +t:done() diff --git a/tests/codecs/zstd.luau b/tests/codecs/zstd.luau new file mode 100644 index 0000000..8e25cf6 --- /dev/null +++ b/tests/codecs/zstd.luau @@ -0,0 +1,115 @@ +-- codecs/Zstd tests: every fixture case (the zstd CLI at levels 1..19, --ultra -22, --fast, --long, small windows, +-- with / without checksum and content size, multi-frame and skippable frames, empty input) decodes to its corpus; +-- offsets / consumedEnd; XXH64 vectors; checksum, limit and error codes; truncated / corrupted / random input never +-- throws. Fixtures: tools/fixtures/zstd.py. +local T = require("@tests/T") +local Zstd = require("@formats/codecs/Zstd") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/zstd") + +local t = T.suite("zstd") + +-- XXH64 reference values (xxhsum -H64) +do + local function hex(s: string): string + local hi, lo = Zstd.xxh64(buffer.fromstring(s)) + return string.format("%08x%08x", hi, lo) + end + t:eq(hex(""), "ef46db3751d8e999", "xxh64 empty") + t:eq(hex("a"), "d24ec4f1a98c6e5b", "xxh64 a") + t:eq(hex("abc"), "44bc2cf5ad770999", "xxh64 abc") + t:eq(hex("Nobody inspects the spammish repetition"), "fbcea83c8a378bf1", "xxh64 sentence") + t:eq(hex(string.rep("0123456789", 10)), "f80e7b96315afffa", "xxh64 100 bytes") +end + +-- every case decodes to its corpus +local nbytes = 0 +for _, c in Fx.cases do + local want = Fx.corpora[c.corpus] + local b = buffer.fromstring(c.data) + local out, consumed = Zstd.decompress(b) + t:check(out ~= nil, c.name .. ": " .. tostring(consumed)) + t:check(buffer.tostring(out :: buffer) == want, c.name .. ": output differs") + t:eq(consumed, #c.data, c.name .. ": consumed") + nbytes += #want +end +t:note("%d fixture streams, %.1f MB decoded", #Fx.cases, nbytes / 1e6) + +local function case(name: string): any + for _, c in Fx.cases do + if c.name == name then + return c + end + end + error("no case " .. name) +end + +-- at an offset inside a bigger buffer, and string input +do + local c = case("text/l3") + local big = buffer.create(#c.data + 20) + buffer.fill(big, 0, 0xAB) + buffer.writestring(big, 7, c.data) + local out, consumed = Zstd.decompress(big, 7, #c.data) + t:check(out and buffer.tostring(out) == Fx.corpora.text, "at an offset") + t:eq(consumed, 7 + #c.data, "consumed at an offset") + t:check(buffer.tostring((Zstd.decompress(c.data))) == Fx.corpora.text, "string input") + t:check(Zstd.isFrame(buffer.fromstring(c.data)), "isFrame") + t:check(not Zstd.isFrame(buffer.fromstring("abcd")), "isFrame on other data") + -- trailing garbage is an error, as zstd -d says + local _, e = Zstd.decompress(c.data .. "junk") + t:check(e and e.code == Err.CORRUPT, "trailing garbage: " .. tostring(e)) +end + +-- checksum mismatch (the last 4 bytes), and verify = false skips it +do + local c = case("text/l9") + local b = buffer.fromstring(c.data) + local n = buffer.len(b) + buffer.writeu8(b, n - 1, bit32.bxor(buffer.readu8(b, n - 1), 0x10)) + local out, e = Zstd.decompress(b) + t:check(out == nil and Err.is(e) and e.code == Err.CHECKSUM, "checksum mismatch: " .. tostring(e)) + local out2 = Zstd.decompress(b, nil, nil, { verify = false }) + t:check(out2 and buffer.tostring(out2) == Fx.corpora.text, "verify = false") +end + +-- limits and arguments +do + local c = case("text/l3") + local _, e = Zstd.decompress(c.data, nil, nil, { maxBytes = 1000 }) + t:check(e and e.code == Err.LIMIT, "maxBytes with a content size: " .. tostring(e)) + local s = case("text/stdin") + local _, e2 = Zstd.decompress(s.data, nil, nil, { maxBytes = 1000 }) + t:check(e2 and e2.code == Err.LIMIT, "maxBytes without a content size: " .. tostring(e2)) + local ok, r1, r2 = pcall(Zstd.decompress, 5 :: any) + t:check(ok and r1 == nil and r2.code == Err.ARG, "a non-buffer argument returns Err.ARG") + local _, e3 = Zstd.decompress("") + t:check(e3 and e3.code == Err.TRUNCATED, "empty input is TRUNCATED: " .. tostring(e3)) + local _, e4 = Zstd.decompress("\40\181\47\253\0") + t:check(e4 and e4.code == Err.TRUNCATED, "header only: " .. tostring(e4)) + -- a dictionary ID: FHD with Dictionary_ID_flag = 1, single segment, then a 1-byte dictionary id and 1-byte size + local _, e5 = Zstd.decompress("\40\181\47\253\33\7\0\1\0\0") + t:check(e5 and e5.code == Err.UNSUPPORTED, "dictionary: " .. tostring(e5)) + -- reserved block type + local _, e6 = Zstd.decompress("\40\181\47\253\32\0\7\0\0") + t:check(e6 and e6.code == Err.CORRUPT, "reserved block type: " .. tostring(e6)) +end + +-- truncation, corruption and garbage never throw +do + local samples = {} + for i, c in Fx.cases do + if i % 5 == 0 and #c.data > 8 and #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decompress", function(b: buffer) + return Zstd.decompress(b) + end, samples, { mutations = 12, garbage = 2000 }) + -- keep the frame header intact so the mutations reach the blocks + t:fuzz("decompress (blocks)", function(b: buffer) + return Zstd.decompress(b, nil, nil, { verify = false, maxBytes = 1e6 }) + end, samples, { mutations = 40, garbage = 0, keepHeader = 12, seed = 99 }) +end + +t:done() diff --git a/tools/fixtures/zstd.py b/tools/fixtures/zstd.py new file mode 100644 index 0000000..afaa29c --- /dev/null +++ b/tools/fixtures/zstd.py @@ -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)})