diff --git a/docs/FORMATS.md b/docs/FORMATS.md index b1ce9d3..2d551b9 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -56,6 +56,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | archive | cpio | .cpio | yes | yes | variants: "newc", "crc", "odc", "bin" | `tests/archive/cpio.luau` | | archive | gzip | .gz .tgz .gzip | yes | yes | stream: true | `tests/archive/gzip.luau` | | archive | iso | .iso | yes | - | extensions: "joliet", "rockridge", "eltorito" | `tests/archive/iso.luau` | +| archive | lz4 | .lz4 .tlz4 | yes | yes | stream: true, legacy: true | `tests/archive/lz4.luau` | | archive | rpm | .rpm | yes | - | compressors: "gzip", "bzip2", "xz", "lzma", "zstd" | `tests/archive/rpm.luau` | | archive | tar | .tar | yes | yes | variants: "ustar", "pax", "gnu" | `tests/archive/tar.luau` | | archive | xz | .xz .txz .lzma | yes | - | stream: true, filters: "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" | `tests/archive/xz.luau` | @@ -113,6 +114,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - 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 - codecs/compress/UnixCompress: the LZW of Unix compress (.Z files: magic 1F 9D, a flags byte with the maximum code + - codecs/compress/Xxh32: XXH32 of a buffer range (any seed), for the LZ4 frame format's header, block and content - codecs/compress/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd - **entropy** - codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders. diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index e3f814e..d2fcb55 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -626,6 +626,18 @@ local list: { Entry } = { return require("@formats/archive/iso") end, }, + { + name = "lz4", + category = "archive", + path = "archive/lz4", + extensions = { "lz4", "tlz4" }, + mime = { "application/x-lz4" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Lz4", "codecs/compress/Xxh32", "containers/Archive" }, + caps = { decode = true, encode = true, stream = true, legacy = true }, + load = function() + return require("@formats/archive/lz4") + end, + }, { name = "rpm", category = "archive", @@ -668,7 +680,7 @@ local list: { Entry } = { path = "archive/z", extensions = { "z", "taz", "tz" }, mime = { "application/x-compress" }, - deps = { "core/Err", "core/Bytes", "codecs/compress/UnixCompress", "containers/Archive", "containers/Tar" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/UnixCompress", "containers/Archive" }, caps = { decode = true, encode = true, stream = true, bits = { 9, 16 } }, load = function() return require("@formats/archive/z") diff --git a/src/Formats/archive/lz4/init.luau b/src/Formats/archive/lz4/init.luau new file mode 100644 index 0000000..099edf0 --- /dev/null +++ b/src/Formats/archive/lz4/init.luau @@ -0,0 +1,353 @@ +--!strict +-- archive/lz4: LZ4 frame files (.lz4: lz4 doc/lz4_Frame_format.md 1.6.x) as a single-stream Archive: one entry (the +-- decompressed data), named after the file without .lz4 (.tlz4 -> .tar), else "data"; meta.stream = true, so the api +-- unwraps a .tar.lz4. Reading: concatenated frames, skippable frames (magic 0x184D2A50..5F, skipped), the legacy +-- frame (magic 0x184C2102, 8 MB blocks), independent and linked blocks, block sizes 64 KB .. 4 MB, uncompressed +-- blocks, the header checksum, block checksums and the content checksum (XXH32, codecs/compress/Xxh32: verified +-- unless opts.verify = false), the content size (checked). Writing: one frame of independent blocks +-- (codecs/compress/Lz4), with opts for the block size, block checksums, the content checksum and the content size; +-- several entries are written as a tar inside. Written from the specification; no code ported. Not supported: +-- dictionaries (frames with a dictionary ID: Err.UNSUPPORTED), writing linked blocks or legacy frames. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Lz4 = require("@formats/codecs/compress/Lz4") +local Xxh32 = require("@formats/codecs/compress/Xxh32") +local Archive = require("@formats/containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Lz4Format = { + name = "lz4", + category = "archive", + extensions = { "lz4", "tlz4" }, + mime = { "application/x-lz4" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Lz4", "codecs/compress/Xxh32", "containers/Archive" }, + caps = { decode = true, encode = true, stream = true, legacy = true }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse output larger than this (default 2^30) + verify: boolean?, -- check the block / content checksums (default true; the header checksum is always checked) + name: string?, -- the file name (the api passes it): names the entry +} +export type EncodeOptions = { + blockSize: number?, -- 65536, 262144, 1048576 or 4194304 (default 4 MB, as the lz4 tool) + blockChecksum: boolean?, -- default false + contentChecksum: boolean?, -- default true + contentSize: boolean?, -- store the content size (default false) +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = 0x184D2204 +local LEGACY = 0x184C2102 +local LEGACY_BLOCK = 8 * 1048576 +local SIZES: { [number]: number } = { [4] = 65536, [5] = 262144, [6] = 1048576, [7] = 4194304 } + +-- ------------------------------------------------------------------------------------------------ sniff +function Lz4Format.sniff(r: Bytes.Reader): number + local m = r:peek(4) + if m == "\4\34\77\24" then + return 1 + elseif m == "\2\33\76\24" then + return 0.9 + elseif #m == 4 and string.byte(m, 1) >= 0x50 and string.byte(m, 1) <= 0x5F and string.sub(m, 2) == "\42\77\24" then + -- a skippable frame (zstd shares the magic): an LZ4 frame after it + local h = r:peek(4, 4) + if #h == 4 then + local n = string.byte(h, 1) + string.byte(h, 2) * 256 + string.byte(h, 3) * 65536 + string.byte(h, 4) * 16777216 + if r:peek(4, 8 + n) == "\4\34\77\24" then + return 1 + end + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function skippable(m: number): boolean + return m >= 0x184D2A50 and m <= 0x184D2A5F +end + +type Out = { buf: buffer, n: number, max: number } + +-- room for k more bytes in the output (doubling, up to max) | false +local function room(out: Out, k: number): boolean + local need = out.n + k + if need > out.max then + return false + end + if need > buffer.len(out.buf) then + local nb = buffer.create(math.min(math.max(buffer.len(out.buf) * 2, need), out.max)) + buffer.copy(nb, 0, out.buf, 0, out.n) + out.buf = nb + end + return true +end + +-- one LZ4 frame at p -> the input offset after it | nil, Err +local function frame(b: buffer, p: number, e: number, out: Out, verify: boolean): (number?, Err.Err?) + if p + 7 > e then + return nil, Err.new(Err.TRUNCATED, "frame header past the end", p) + end + local flg, bd = buffer.readu8(b, p + 4), buffer.readu8(b, p + 5) + if bit32.rshift(flg, 6) ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, "frame version " .. bit32.rshift(flg, 6), p + 4) + end + if bit32.band(flg, 2) ~= 0 or bit32.band(bd, 0x8F) ~= 0 then + return nil, Err.new(Err.CORRUPT, "reserved descriptor bits set", p + 4) + end + local independent = bit32.band(flg, 0x20) ~= 0 + local blockSum = bit32.band(flg, 0x10) ~= 0 + local hasSize = bit32.band(flg, 0x08) ~= 0 + local contentSum = bit32.band(flg, 0x04) ~= 0 + local hasDict = bit32.band(flg, 0x01) ~= 0 + local bmax = SIZES[bit32.rshift(bd, 4)] + if not bmax then + return nil, Err.new(Err.CORRUPT, "bad block maximum size", p + 5) + end + local q = p + 6 + local size: number? = nil + if hasSize then + if q + 8 > e then + return nil, Err.new(Err.TRUNCATED, "frame header past the end", q) + end + size = buffer.readu32(b, q) + buffer.readu32(b, q + 4) * 4294967296 + q += 8 + end + if hasDict then + return nil, Err.new(Err.UNSUPPORTED, "frames with a dictionary", q) + end + if q + 1 > e then + return nil, Err.new(Err.TRUNCATED, "frame header past the end", q) + end + local hc = bit32.band(bit32.rshift(Xxh32.hash(b, p + 4, q - p - 4), 8), 255) + if hc ~= buffer.readu8(b, q) then + return nil, Err.new(Err.CHECKSUM, "frame header checksum mismatch", q) + end + q += 1 + if size and out.n + size > out.max then + return nil, Err.new(Err.LIMIT, "content over " .. out.max .. " bytes", p) + end + local start = out.n + while true do + if q + 4 > e then + return nil, Err.new(Err.TRUNCATED, "block header past the end", q) + end + local bs = buffer.readu32(b, q) + q += 4 + if bs == 0 then + break + end + local raw = bit32.band(bs, 0x80000000) ~= 0 + local n = bit32.band(bs, 0x7FFFFFFF) + if n > bmax then + return nil, Err.new(Err.CORRUPT, "block larger than the maximum", q - 4) + end + if q + n + (if blockSum then 4 else 0) > e then + return nil, Err.new(Err.TRUNCATED, "block past the end", q) + end + if blockSum and verify and Xxh32.hash(b, q, n) ~= buffer.readu32(b, q + n) then + return nil, Err.new(Err.CHECKSUM, "block checksum mismatch", q + n) + end + if not room(out, if raw then n else bmax) and not room(out, if raw then n else math.min(bmax, out.max - out.n)) then + return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q) + end + if raw then + buffer.copy(out.buf, out.n, b, q, n) + out.n += n + else + local lim = math.min(out.n + bmax, buffer.len(out.buf)) + local dEnd, msg = Lz4.decodeInto(b, q, q + n, out.buf, out.n, lim, if independent then out.n else start) + if not dEnd then + if msg and string.sub(msg, 1, 6) == "limit:" and lim < out.n + bmax then + return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q) + end + return nil, Err.from(msg, q) + end + out.n = dEnd + end + q += n + (if blockSum then 4 else 0) + end + if contentSum then + if q + 4 > e then + return nil, Err.new(Err.TRUNCATED, "content checksum past the end", q) + end + if verify and Xxh32.hash(out.buf, start, out.n - start) ~= buffer.readu32(b, q) then + return nil, Err.new(Err.CHECKSUM, "content checksum mismatch", q) + end + q += 4 + end + if size and out.n - start ~= size then + return nil, Err.new(Err.CORRUPT, "content size mismatch", p + 6) + end + return q, nil +end + +-- a legacy frame at p: blocks of up to 8 MB until the input ends or a magic number follows +local function legacy(b: buffer, p: number, e: number, out: Out): (number?, Err.Err?) + local q = p + 4 + while q + 4 <= e do + local n = buffer.readu32(b, q) + if n == MAGIC or n == LEGACY or skippable(n) then + break + end + q += 4 + if q + n > e then + return nil, Err.new(Err.TRUNCATED, "block past the end", q) + end + if not room(out, LEGACY_BLOCK) and not room(out, math.min(LEGACY_BLOCK, out.max - out.n)) then + return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q) + end + local lim = math.min(out.n + LEGACY_BLOCK, buffer.len(out.buf)) + local dEnd, msg = Lz4.decodeInto(b, q, q + n, out.buf, out.n, lim) + if not dEnd then + return nil, Err.from(msg, q) + end + out.n = dEnd + q += n + end + return q, nil +end + +-- decompress(buf, offset?, length?, opts?) -> the data of every frame | nil, Err +function Lz4Format.decompress(src: buffer | string, offset: number?, length: number?, opts: DecodeOptions?): (buffer?, Err.Err?) + local b, o, n, aerr = Bytes.span("Lz4.decompress", src, offset, length) + if not b then + return nil, aerr + end + local maxBytes = (opts and opts.maxBytes) or 2 ^ 30 + local verify = not (opts and opts.verify == false) + local out: Out = { buf = buffer.create(math.min(math.max(n * 3, 256), maxBytes)), n = 0, max = maxBytes } + local p, e = o, o + n + local frames = 0 + while p + 4 <= e do + local m = buffer.readu32(b, p) + local q, err + if m == MAGIC then + q, err = frame(b, p, e, out, verify) + frames += 1 + elseif m == LEGACY then + q, err = legacy(b, p, e, out) + frames += 1 + elseif skippable(m) then + if p + 8 > e then + return nil, Err.new(Err.TRUNCATED, "skippable frame past the end", p) + end + q = p + 8 + buffer.readu32(b, p + 4) + if q > e then + return nil, Err.new(Err.TRUNCATED, "skippable frame past the end", p) + end + elseif frames > 0 then + break -- trailing data after the frames (as lz4 -d, which warns) + else + return nil, Err.new(Err.CORRUPT, "bad magic", p) + end + if not q then + return nil, err + end + p = q :: number + end + if frames == 0 then + return nil, Err.new(if n < 4 then Err.TRUNCATED else Err.CORRUPT, "no LZ4 frame", o) + end + local res = buffer.create(out.n) + buffer.copy(res, 0, out.buf, 0, out.n) + return res, nil +end + +local function encode(value: any, opts: any?): (buffer?, Err.Err?) + return Lz4Format.encode(value, opts) +end + +function Lz4Format.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local n = r.limit - r.base + local out, err = Lz4Format.decompress(r.buf, r.base, n, o) + if not out then + return nil, err + end + local a = Archive.new("lz4", encode) + a.meta.stream = true + a.meta.source = { format = "lz4", legacy = r:peek(4) == "\2\33\76\24" } + local name = Archive.streamName(o, { "lz4" }) + local stem, ext = string.match(name, "^(.+)%.(%w+)$") + if stem and ext and string.lower(ext) == "tlz4" then + name = stem .. ".tar" + end + Archive.put(a, { name = name, size = buffer.len(out), compressedSize = n, method = "lz4", dir = false, data = out }) + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- compress(data, opts?) -> one LZ4 frame | nil, Err +function Lz4Format.compress(data: buffer | string, opts: EncodeOptions?): (buffer?, Err.Err?) + local b, o, n, aerr = Bytes.span("Lz4.compress", data, nil, nil) + if not b then + return nil, aerr + end + local op: EncodeOptions = opts or {} + local bsize = op.blockSize or 4194304 + local bd = nil + for k, v in SIZES do + if v == bsize then + bd = k + end + end + if not bd then + return nil, Err.new(Err.ARG, "blockSize must be 65536, 262144, 1048576 or 4194304") + end + local blockSum = op.blockChecksum == true + local contentSum = op.contentChecksum ~= false + local withSize = op.contentSize == true + local w = Bytes.writer(n + n // 200 + 64) + w:u32le(MAGIC) + local flg = 0x40 + 0x20 + (if blockSum then 0x10 else 0) + (if withSize then 0x08 else 0) + (if contentSum then 0x04 else 0) + w:u8(flg) + w:u8(bd * 16) + if withSize then + w:u32le(n % 4294967296) + w:u32le(n // 4294967296) + end + local hc = bit32.band(bit32.rshift(Xxh32.hash(w.buf, 4, w.pos - 4), 8), 255) + w:u8(hc) + local scratch = buffer.create(Lz4.bound(math.min(bsize, math.max(n, 1)))) + local p = o + while p < o + n do + local k = math.min(bsize, o + n - p) + local c = Lz4.encodeInto(b, p, k, scratch, 0) + local at = w.pos + if c < k then + w:u32le(c) + local q = w:reserve(c) + buffer.copy(w.buf, q, scratch, 0, c) + w.pos = q + c + else + w:u32le(k + 0x80000000) + local q = w:reserve(k) + buffer.copy(w.buf, q, b, p, k) + w.pos = q + k + end + if blockSum then + local len = w.pos - at - 4 + w:u32le(Xxh32.hash(w.buf, at + 4, len)) + end + p += k + end + w:u32le(0) + if contentSum then + w:u32le(Xxh32.hash(b, o, n)) + end + return w:finish(), nil +end + +-- encode(value, opts?): a buffer / string, an Archive's one file, or a tar of the Archive's entries, as one frame +function Lz4Format.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local data, err = Archive.streamData(value) + if not data then + return nil, err + end + return Lz4Format.compress(data, opts) +end + +return Lz4Format diff --git a/src/Formats/archive/z/init.luau b/src/Formats/archive/z/init.luau index 903870c..c1a13a5 100644 --- a/src/Formats/archive/z/init.luau +++ b/src/Formats/archive/z/init.luau @@ -10,7 +10,6 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local UnixCompress = require("@formats/codecs/compress/UnixCompress") local Archive = require("@formats/containers/Archive") -local Tar = require("@formats/containers/Tar") -- ------------------------------------------------------------------------------------------------ contract local Z = { @@ -18,7 +17,7 @@ local Z = { category = "archive", extensions = { "z", "taz", "tz" }, mime = { "application/x-compress" }, - deps = { "core/Err", "core/Bytes", "codecs/compress/UnixCompress", "containers/Archive", "containers/Tar" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/UnixCompress", "containers/Archive" }, caps = { decode = true, encode = true, stream = true, bits = { 9, 16 } }, } @@ -76,38 +75,8 @@ function Z.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- the data to compress: a buffer / string, an Archive's one file, or a tar of its entries -local function payload(value: any): (buffer?, Err.Err?) - if type(value) == "buffer" then - return value, nil - elseif type(value) == "string" then - return buffer.fromstring(value), nil - end - local items = Archive.entries(value) - if not items then - return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string") - end - if #items == 1 and not items[1].entry.dir then - return items[1].read() - end - local list = {} - for _, it in items do - local e: any = it.entry - local data: buffer? = nil - if not e.dir and (e.type == nil or e.type == "0") then - local b, err = it.read() - if not b then - return nil, err - end - data = b - end - table.insert(list, { name = e.name, data = data, dir = e.dir, type = e.type, link = e.link, mtime = e.mtime, mode = e.mode }) - end - return Tar.write(list) -end - function Z.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) - local data, err = payload(value) + local data, err = Archive.streamData(value) if not data then return nil, err end diff --git a/src/Formats/codecs/compress/Xxh32.luau b/src/Formats/codecs/compress/Xxh32.luau new file mode 100644 index 0000000..121a6f8 --- /dev/null +++ b/src/Formats/codecs/compress/Xxh32.luau @@ -0,0 +1,72 @@ +--!strict +--!native +--!optimize 2 +-- codecs/compress/Xxh32: XXH32 of a buffer range (any seed), for the LZ4 frame format's header, block and content +-- checksums. 32 x 32 -> 32 products split one operand into 16-bit limbs so every partial product is exact in a double. +-- From the xxHash specification (Yann Collet, BSD-2); no code copied. Never throws (the range is clamped to the buffer). +-- +-- local h = Xxh32.hash(buf, offset?, length?, seed?) -- a number in 0 .. 2^32 - 1 +local Xxh32 = {} + +local bxor, bor, lshift, rshift = bit32.bxor, bit32.bor, bit32.lshift, bit32.rshift +local readu8, readu32 = buffer.readu8, buffer.readu32 + +local T32 = 4294967296 +local P1, P2, P3, P4, P5 = 0x9E3779B1, 0x85EBCA77, 0xC2B2AE3D, 0x27D4EB2F, 0x165667B1 + +-- a * b mod 2^32 (a, b below 2^32) +local function mul(a: number, b: number): number + local a0 = a % 65536 + local a1 = (a - a0) / 65536 + return (a0 * b + ((a1 * b) % 65536) * 65536) % T32 +end + +local function rotl(x: number, r: number): number + return bor(lshift(x, r), rshift(x, 32 - r)) +end + +local function round(acc: number, lane: number): number + return mul(rotl((acc + mul(lane, P2)) % T32, 13), P1) +end + +-- hash(buf, offset?, length?, seed?) -> XXH32 +function Xxh32.hash(b: buffer, offset: number?, length: number?, seed: number?): number + local n0 = buffer.len(b) + local o = math.clamp(offset or 0, 0, n0) + local n = math.clamp(length or (n0 - o), 0, n0 - o) + local s = (seed or 0) % T32 + local p = o + local e = o + n + local h + if n >= 16 then + local v1 = (s + P1 + P2) % T32 + local v2 = (s + P2) % T32 + local v3 = s + local v4 = (s - P1) % T32 + local last = e - 16 + while p <= last do + v1 = round(v1, readu32(b, p)) + v2 = round(v2, readu32(b, p + 4)) + v3 = round(v3, readu32(b, p + 8)) + v4 = round(v4, readu32(b, p + 12)) + p += 16 + end + h = (rotl(v1, 1) + rotl(v2, 7) + rotl(v3, 12) + rotl(v4, 18)) % T32 + else + h = (s + P5) % T32 + end + h = (h + n) % T32 + while p + 4 <= e do + h = mul(rotl((h + mul(readu32(b, p), P3)) % T32, 17), P4) + p += 4 + end + while p < e do + h = mul(rotl((h + readu8(b, p) * P5) % T32, 11), P1) + p += 1 + end + h = mul(bxor(h, rshift(h, 15)), P2) + h = mul(bxor(h, rshift(h, 13)), P3) + return bxor(h, rshift(h, 16)) +end + +return Xxh32 diff --git a/src/Formats/containers/Archive.luau b/src/Formats/containers/Archive.luau index ef9a63d..cc46239 100644 --- a/src/Formats/containers/Archive.luau +++ b/src/Formats/containers/Archive.luau @@ -13,6 +13,7 @@ -- (a .tar.gz loads as the tar inside). Never throws: read of a missing entry or a failed loader returns nil, Err. local Err = require("@formats/core/Err") local Types = require("@formats/Types") +local Tar = require("@formats/containers/Tar") local Archive = {} @@ -152,6 +153,38 @@ function Archive.entries(value: any): { { entry: Types.ArchiveEntry, read: () -> return out end +-- streamData(value) -> what a single-stream encoder compresses: a buffer / string as it is, an Archive's one file, or +-- a tar of the Archive's entries (files, directories, symlinks with their mode / mtime) | nil, Err +function Archive.streamData(value: any): (buffer?, Err.Err?) + if type(value) == "buffer" then + return value, nil + elseif type(value) == "string" then + return buffer.fromstring(value), nil + end + local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string") + end + if #items == 1 and not items[1].entry.dir then + return items[1].read() + end + local list = {} + for _, it in items do + local e: any = it.entry + local data: buffer? = nil + if not e.dir and (e.type == nil or e.type == "0") then + local b, err = it.read() + if not b then + return nil, err + end + data = b + end + local typ = if type(e.type) == "string" and #e.type == 1 then e.type else nil + table.insert(list, { name = e.name, data = data, dir = e.dir, type = typ, link = e.link, mtime = e.mtime, mode = e.mode }) + end + return Tar.write(list) +end + -- streamName(opts, ext) -> the entry name for a single-stream archive: opts.name without its compression extension -- (".tgz" -> ".tar"), else "data" function Archive.streamName(opts: any?, exts: { string }): string diff --git a/tests/archive/lz4.luau b/tests/archive/lz4.luau new file mode 100644 index 0000000..834e3bb --- /dev/null +++ b/tests/archive/lz4.luau @@ -0,0 +1,119 @@ +-- archive/lz4 tests (and codecs/compress/Xxh32): frames from the lz4 tool (default, linked blocks, 64 KB blocks, block +-- checksums, content size, no content checksum, HC, legacy), concatenated and skippable frames decode to their corpora; +-- our frames (every option set) decode with `lz4 -d` (verdicts from the fixture step) and round-trip; XXH32 test +-- vectors; checksum / size / truncation errors; the api (.tar.lz4 unwrap, naming); the fuzz pass. +-- Fixtures: tools/fixtures/lz4frame.py. +local T = require("@tests/T") +local F = require("@formats") +local Lz4F = require("@formats/archive/lz4") +local Xxh32 = require("@formats/codecs/compress/Xxh32") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/lz4frame") +local C = require("@tests/gen/lz4frame_corpora") + +local t = T.suite("lz4") +t:eq(Lz4F.name, "lz4", "name") + +-- XXH32 vectors (xxHash's sanity checks) +t:eq(Xxh32.hash(buffer.fromstring("")), 0x02CC5D05, "xxh32 empty") +t:eq(Xxh32.hash(buffer.fromstring(""), 0, 0, 0x9E3779B1), 0x36B78AE7, "xxh32 empty, seed prime") +t:eq(Xxh32.hash(buffer.fromstring("a")), 0x550D7456, "xxh32 a") +t:eq(Xxh32.hash(buffer.fromstring("abc")), 0x32D153FF, "xxh32 abc") +t:eq(Xxh32.hash(buffer.fromstring("Nobody inspects the spammish repetition")), 0xE2293B2F, "xxh32 sentence") + +local function want(c: any): string + if c.corpus == "short+text" then + return C.short .. C.text + end + return C[c.corpus] +end + +for _, c in Fx.cases do + local out, err = Lz4F.decompress(c.data) + t:check(out, c.name .. ": " .. tostring(err)) + local w = want(c) + t:eq(buffer.len(out), #w, c.name .. ": size") + t:eq(Crc32.of(out), Crc32.of(buffer.fromstring(w)), c.name .. ": data") + t:eq(F.detect(c.data), "lz4", c.name .. ": F.detect") +end + +-- our frames, read by lz4 -d +t:check(#Fx.ours >= 15, "verdicts present") +for _, v in Fx.ours do + t:check(v.ok, "lz4 -d reads our " .. v.name) +end +for name, data in C do + for _, o in { {}, { blockSize = 65536, blockChecksum = true, contentSize = true }, { contentChecksum = false } } do + local z = assert(Lz4F.compress(data, o :: any)) + t:eq(buffer.tostring(assert(Lz4F.decompress(z))), data, "round trip " .. name) + end +end + +-- the api +do + local a = assert(F.load(Fx.cases[1].data, { name = "notes.txt.lz4" })) + t:check(a.meta.stream and a.format == "lz4", "single stream") + t:eq(a:list()[1].name, "notes.txt", "entry named after the file") + local tar = F.format("tar").new() + tar:add("a.txt", "alpha") + tar:add("b.txt", "beta") + local tl = assert(F.save(tar, nil, { format = "lz4" })) + local back = F.load(tl, { name = "x.tlz4" }) + t:eq(back.format, "tar", "several entries: a .tar.lz4 that unwraps") + t:eq(back.meta.compression, "lz4", "meta.compression") + t:eq(F.load(tl, { name = "x.tlz4", unwrap = false }):list()[1].name, "x.tar", ".tlz4 -> .tar") + local s = assert(F.save("some text", nil, { format = "lz4" })) + t:eq(buffer.tostring(F.load(s):read("data")), "some text", "a string") +end + +-- errors +do + local good + for _, c in Fx.cases do + if c.name == "text/BX" then + good = c.data + end + end + local function flip(at: number): buffer + local b = buffer.fromstring(good) + buffer.writeu8(b, at, bit32.bxor(buffer.readu8(b, at), 1)) + return b + end + local _, e1 = Lz4F.decompress(flip(6)) + t:check(e1 and e1.code == Err.CHECKSUM, "header checksum: " .. tostring(e1)) + local _, e2 = Lz4F.decompress(flip(20)) + t:check(e2 and e2.code == Err.CHECKSUM, "block checksum: " .. tostring(e2)) + local _, e3 = Lz4F.decompress(flip(#good - 2)) + t:check(e3 and e3.code == Err.CHECKSUM, "content checksum: " .. tostring(e3)) + t:check(Lz4F.decompress(flip(#good - 2), nil, nil, { verify = false }), "verify = false") + local _, e4 = Lz4F.decompress(string.sub(good, 1, 1000)) + t:check(e4 and e4.code == Err.TRUNCATED, "truncated: " .. tostring(e4)) + local _, e5 = Lz4F.decompress(Fx.cases[1].data, nil, nil, { maxBytes = 10 }) + t:check(e5 == nil or e5.code == Err.LIMIT, "maxBytes") + local big + for _, c in Fx.cases do + if c.name == "zeros/default" then + big = c.data + end + end + local _, e6 = Lz4F.decompress(big, nil, nil, { maxBytes = 1000 }) + t:check(e6 and e6.code == Err.LIMIT, "maxBytes: " .. tostring(e6)) + local _, e7 = Lz4F.compress("x", { blockSize = 1000 }) + t:check(e7 and e7.code == Err.ARG, "bad blockSize") + local _, e8 = Lz4F.decompress("not lz4 at all") + t:check(e8 and e8.code == Err.CORRUPT, "bad magic") +end + +local samples = {} +for _, c in Fx.cases do + if #c.data < 6000 then + table.insert(samples, c.data) + end +end +t:fuzz("decode", function(b: buffer) + return Lz4F.decode(Bytes.reader(b), { maxBytes = 2 ^ 22 }) +end, samples, { mutations = 40, keepHeader = 4 }) + +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 6db61a2..f1effb8 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -267,6 +267,24 @@ do Bzip2.decompress(bz) end) end +do + local Lz4F = require("@formats/archive/lz4") + local LF = require("@tests/gen/lz4frame") + local LC = require("@tests/gen/lz4frame_corpora") + local frameData + for _, c in LF.cases do + if c.name == "text/BX" then + frameData = buffer.fromstring(c.data) + end + end + bench("lz4 frame decode (64K, xxh32)", 5, #LC.text, function() + Lz4F.decompress(frameData) + end) + local tb = buffer.fromstring(LC.text) + bench("lz4 frame encode (xxh32)", 5, #LC.text, function() + Lz4F.compress(tb) + end) +end do local UnixCompress = require("@formats/codecs/compress/UnixCompress") local ZC = require("@tests/gen/z") diff --git a/tools/fixtures/_lz4frame_encode.luau b/tools/fixtures/_lz4frame_encode.luau new file mode 100644 index 0000000..0c17f13 --- /dev/null +++ b/tools/fixtures/_lz4frame_encode.luau @@ -0,0 +1,21 @@ +-- tools/fixtures/_lz4frame_encode.luau: run by tools/fixtures/lz4frame.py under the luau CLI: writes every corpus of +-- tests/gen/lz4frame_corpora as LZ4 frames with archive/lz4 (several option sets) and prints " " lines for +-- the lz4 tool to decompress. +local Lz4F = require("@formats/archive/lz4") +local C = require("@tests/gen/lz4frame_corpora") + +local sets = { + default = {}, + b64k = { blockSize = 65536, blockChecksum = true, contentSize = true }, + nocrc = { contentChecksum = false, blockSize = 262144 }, +} +for name, data in C do + for sname, o in sets do + local b = assert(Lz4F.compress(data, o :: any)) + 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 .. "/" .. sname .. " " .. table.concat(t)) + end +end diff --git a/tools/fixtures/lz4frame.py b/tools/fixtures/lz4frame.py new file mode 100644 index 0000000..5ba064c --- /dev/null +++ b/tools/fixtures/lz4frame.py @@ -0,0 +1,72 @@ +# LZ4 frame fixtures (tools/fixtures.py): corpora compressed by the lz4 tool 1.10 (nixpkgs#lz4) with its frame options +# (default, linked blocks -BD, 64 KB blocks -B4 with and without -BD, block checksums -BX, --content-size, +# --no-frame-crc, -9, the legacy format -l), concatenated frames and a skippable frame; and our writer's frames +# (tools/fixtures/_lz4frame_encode.luau under the luau CLI) decompressed by `lz4 -d`, as verdicts. +# tests/gen/lz4frame.luau { cases = { { name, corpus, data } }, ours = { { name, ok } } } +# tests/gen/lz4frame_corpora.luau { [name] = bytes } +import os, shutil, struct, subprocess, tempfile + +INPUTS = ["src/Formats/archive/lz4/init.luau", "src/Formats/codecs/compress/Lz4.luau", "src/Formats/codecs/compress/Xxh32.luau", + "tools/fixtures/_lz4frame_encode.luau"] + + +def lz4(args, data=None, path=None): + argv = ["nix", "shell", "nixpkgs#lz4", "-c", "lz4"] + args + ([path] if path else []) + return subprocess.run(argv, input=data, capture_output=True, check=True).stdout + + +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) >= 160000: + break + return {"empty": b"", "short": b"hello, lz4 frames\n", "text": bytes(text[:160000]), "random": rng.randbytes(20000), + "zeros": b"\0" * 300000} + + +def luau_cmd(): + exe = shutil.which("luau") + return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"] + + +def generate(ctx): + cs = corpora(ctx.rng(43)) + cases = [] + tmp = tempfile.mkdtemp() + try: + for name, data in cs.items(): + path = os.path.join(tmp, name) + with open(path, "wb") as f: + f.write(data) + variants = [("default", ["-c"])] + if name in ("text", "zeros", "short"): + variants += [("BD", ["-c", "-BD"]), ("B4", ["-c", "-B4"]), ("B4BD", ["-c", "-B4", "-BD"]), ("BX", ["-c", "-B4", "-BX"]), + ("size", ["-c", "--content-size"]), ("nocrc", ["-c", "--no-frame-crc"]), ("hc9", ["-c", "-9", "-B4", "-BD"]), + ("legacy", ["-c", "-l"])] + for vname, args in variants: + cases.append({"name": name + "/" + vname, "corpus": name, "data": lz4(args, path=path)}) + finally: + shutil.rmtree(tmp) + # two frames, and a skippable frame in front + two = lz4(["-c"], data=cs["short"]) + lz4(["-c", "-B4"], data=cs["text"]) + cases.append({"name": "concat", "corpus": "short+text", "data": two}) + skip = struct.pack("