ws-arch2-unix: archive/lz4 (LZ4 frame read: linked / independent blocks, block / content XXH32, content size, skippable + legacy frames, concatenation; write: independent blocks) on codecs/compress/Lz4 (merged from ws/roblox ba4b20e) + codecs/compress/Xxh32; containers/Archive.streamData (shared single-stream payload: buffer / one entry / tar of entries; used by z and lz4); tests vs the lz4 tool both ways; bench lines

containers/Archive: additive helper streamData (requires containers/Tar); nothing existing changes.
This commit is contained in:
4DBug committed 2026-10-31 14:40:26 -05:00
1 parent 197ddc561a
commit 411261470a
10 files changed
+705 -34

No files matched your search

+13 -1
View File
@@ -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")
+353
View File
@@ -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
+2 -33
View File
@@ -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
+72
View File
@@ -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
+33
View File
@@ -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