merge ws/arch2-unix (cpio, ar/deb, rpm, z, iso, lz4; containers/Cpio, Iso9660; codecs UnixCompress, Xxh32, Lz4 from ws/roblox)

This commit is contained in:
4DBug committed 2026-10-31 15:22:07 -05:00
commit 242e38c4fe
36 files changed
+5171 -7

No files matched your search

+291
View File
@@ -0,0 +1,291 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md): decode and a greedy hash-chain-free encoder
-- (the reference "fast" strategy: one 4-byte hash table, 64 KB window). A codec (layer 3): model/rbxm chunk bodies,
-- and the LZ4 frame format (archive) builds on it. New code, written from the specification. Never throws.
--
-- local out, err = Lz4.decompress(src, offset?, length?, outSize?, opts?) -- a block -> buffer | nil, Err
-- local packed = Lz4.compress(src, offset?, length?) -- -> buffer (a block) | nil, Err
-- local dEnd, msg = Lz4.decodeInto(src, p, limit, dst, d, dstLimit, histStart?) -- low level (linked blocks)
-- local n = Lz4.encodeInto(src, p, n, dst, d) -- low level; dst has bound(n) room
-- Lz4.bound(n) -- worst-case block size for n bytes
--
-- decodeInto decodes one block from src[p, limit) to dst[d, dstLimit): matches may reach back to histStart (default
-- d), so a frame decoder with linked blocks keeps the previous output in front of d. It returns the output end, or
-- nil and a message ("truncated", "corrupt: ...", "limit: output ...") for the caller's Err.from.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Lz4 = {}
export type Options = {
maxBytes: number?, -- refuse output larger than this when outSize is not given (default 2^28)
}
local readu8, writeu8, readu16, writeu16, readu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32
local bcopy, bcreate, blen = buffer.copy, buffer.create, buffer.len
local band, rshift = bit32.band, bit32.rshift
local MINMATCH = 4
local LASTLITERALS = 5 -- the last 5 bytes are always literals
local MFLIMIT = 12 -- the last match starts at least 12 bytes before the end
local MAX_OFFSET = 65535
local HASH_BITS = 13
local HASH_SIZE = 2 ^ HASH_BITS
-- ------------------------------------------------------------------------------------------------ decode
function Lz4.decodeInto(src: buffer, p: number, limit: number, dst: buffer, d: number, dstLimit: number, histStart: number?): (number?, string?)
local lo = histStart or d
if limit > blen(src) or dstLimit > blen(dst) or p < 0 or d < 0 or lo < 0 or lo > d then
return nil, "corrupt: bad ranges"
end
if p >= limit then
return nil, "truncated: empty block"
end
while true do
if p >= limit then
return nil, "truncated"
end
local token = readu8(src, p)
p += 1
local lit = rshift(token, 4)
if lit == 15 then
local b = 255
while b == 255 do
if p >= limit then
return nil, "truncated"
end
b = readu8(src, p)
p += 1
lit += b
end
end
if lit > 0 then
if p + lit > limit then
return nil, "truncated: literals past the end"
end
if d + lit > dstLimit then
return nil, "limit: output larger than expected"
end
bcopy(dst, d, src, p, lit)
p += lit
d += lit
end
if p >= limit then
return d, nil -- the last sequence has no match
end
if p + 2 > limit then
return nil, "truncated"
end
local off = readu16(src, p)
p += 2
if off == 0 or d - off < lo then
return nil, "corrupt: bad match offset"
end
local ml = band(token, 15)
if ml == 15 then
local b = 255
while b == 255 do
if p >= limit then
return nil, "truncated"
end
b = readu8(src, p)
p += 1
ml += b
end
end
ml += MINMATCH
if d + ml > dstLimit then
return nil, "limit: output larger than expected"
end
local s = d - off
if off >= ml then
bcopy(dst, d, dst, s, ml)
d += ml
elseif off == 1 then
buffer.fill(dst, d, readu8(dst, s), ml)
d += ml
else
-- an overlapping match repeats the off-byte pattern: copy what is already there, doubling each time
local n = ml
while n > 0 do
local c = d - s
if c > n then
c = n
end
bcopy(dst, d, dst, s, c)
d += c
n -= c
end
end
end
end
-- decompress(src, offset?, length?, outSize?, opts?) -> buffer | nil, Err: one block. With outSize the output must be
-- exactly that long (CORRUPT otherwise); without it the output grows up to opts.maxBytes.
function Lz4.decompress(src: buffer | string, offset: number?, length: number?, outSize: number?, opts: Options?): (buffer?, Err.Err?)
local b, o, l, aerr = Bytes.span("Lz4.decompress", src, offset, length)
if not b then
return nil, aerr
end
if outSize ~= nil then
if type(outSize) ~= "number" or outSize < 0 or outSize % 1 ~= 0 then
return nil, Err.new(Err.ARG, "Lz4.decompress: bad outSize")
end
local out = bcreate(outSize)
local e, msg = Lz4.decodeInto(b, o, o + l, out, 0, outSize)
if not e then
return nil, Err.from(msg, o)
end
if e ~= outSize then
return nil, Err.new(Err.CORRUPT, string.format("block decodes to %d bytes, expected %d", e, outSize), o)
end
return out, nil
end
local max = (opts and opts.maxBytes) or 2 ^ 28
local size = math.min(math.max(l * 4, 256), max)
while true do
local out = bcreate(size)
local e, msg = Lz4.decodeInto(b, o, o + l, out, 0, size)
if e then
local res = bcreate(e)
bcopy(res, 0, out, 0, e)
return res, nil
end
if not (msg and string.sub(msg, 1, 6) == "limit:") then
return nil, Err.from(msg, o)
end
if size >= max then
return nil, Err.new(Err.LIMIT, "output over " .. max .. " bytes", o)
end
size = math.min(size * 4, max)
end
end
-- ------------------------------------------------------------------------------------------------ encode
-- bound(n) -> the largest block n input bytes can produce
function Lz4.bound(n: number): number
return n + n // 255 + 16
end
-- writes a length's 255-run extension at o; returns the next offset
local function extend(dst: buffer, o: number, n: number): number
while n >= 255 do
writeu8(dst, o, 255)
o += 1
n -= 255
end
writeu8(dst, o, n)
return o + 1
end
-- hash(v) -> 1 .. HASH_SIZE: Knuth's multiplicative hash (v * 2654435761 mod 2^32, top bits), exact in doubles
local function hash(v: number): number
local vl, vh = band(v, 0xFFFF), rshift(v, 16)
local mid = (vh * 0x79B1 + vl * 0x9E37) % 65536
return ((vl * 0x79B1 + mid * 65536) % 4294967296) // (2 ^ (32 - HASH_BITS)) + 1
end
local hashTable: { number } = table.create(HASH_SIZE, -1e9)
-- encodeInto(src, p, n, dst, d) -> the block's length: src[p, p + n) compressed to dst[d ..] (room for bound(n))
function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: number): number
local op = d
local anchor = p
local iend = p + n
local ht = hashTable
for i = 1, HASH_SIZE do
ht[i] = -1e9
end
if n >= MFLIMIT + 1 then
local mflimit = iend - MFLIMIT -- a match starts before this
local matchEnd = iend - LASTLITERALS -- and ends at or before this
local ip = p
local skip = 64
while ip < mflimit do
local v = readu32(src, ip)
local h = hash(v)
local ref = ht[h]
ht[h] = ip
if ref >= p and ip - ref <= MAX_OFFSET and readu32(src, ref) == v then
-- back over equal bytes before the match (into the pending literals)
while ip > anchor and ref > p and readu8(src, ip - 1) == readu8(src, ref - 1) do
ip -= 1
ref -= 1
end
local a = ip + MINMATCH
local bpos = ref + MINMATCH
while a + 4 <= matchEnd and readu32(src, a) == readu32(src, bpos) do
a += 4
bpos += 4
end
while a < matchEnd and readu8(src, a) == readu8(src, bpos) do
a += 1
bpos += 1
end
local ml = a - ip
local lit = ip - anchor
local tok = op
op += 1
local tl = if lit >= 15 then 15 else lit
if lit >= 15 then
op = extend(dst, op, lit - 15)
end
if lit > 0 then
bcopy(dst, op, src, anchor, lit)
op += lit
end
writeu16(dst, op, ip - ref)
op += 2
local m = ml - MINMATCH
local tm = if m >= 15 then 15 else m
if m >= 15 then
op = extend(dst, op, m - 15)
end
writeu8(dst, tok, tl * 16 + tm)
ip = a
anchor = ip
skip = 64
-- index the position just before the next one (better ratio at no cost)
if ip - 2 >= p and ip - 2 < mflimit then
local w = readu32(src, ip - 2)
ht[hash(w)] = ip - 2
end
else
ip += rshift(skip, 6) -- step up over incompressible data (the reference's acceleration)
skip += 1
end
end
end
-- the last literals
local lit = iend - anchor
local tok = op
op += 1
if lit >= 15 then
op = extend(dst, op, lit - 15)
writeu8(dst, tok, 0xF0)
else
writeu8(dst, tok, lit * 16)
end
if lit > 0 then
bcopy(dst, op, src, anchor, lit)
op += lit
end
return op - d
end
-- compress(src, offset?, length?) -> buffer (one block) | nil, Err
function Lz4.compress(src: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?)
local b, o, l, aerr = Bytes.span("Lz4.compress", src, offset, length)
if not b then
return nil, aerr
end
local tmp = bcreate(Lz4.bound(l))
local n = Lz4.encodeInto(b, o, l, tmp, 0)
local out = bcreate(n)
bcopy(out, 0, tmp, 0, n)
return out, nil
end
return Lz4
@@ -0,0 +1,319 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/UnixCompress: the LZW of Unix compress (.Z files: magic 1F 9D, a flags byte with the maximum code
-- width 9..16 and the block mode bit), decode and encode. A codec (layer 3): archive/z builds on it. Codes are
-- LSB-first, 9 bits wide at the start; the width grows when the next free code passes 2^width - 1 (up to the
-- maximum), and in block mode code 256 clears the table. compress writes codes in groups of eight: when the width
-- changes or a CLEAR is read, the rest of the current group (counted from the previous change) is skipped. The encoder
-- reproduces ncompress 5.0 bit for bit: greedy longest match, a full table frozen until the compression ratio checked
-- every 10000 input bytes drops, then a CLEAR. Written from the ncompress sources (public domain, The Unlicense: read
-- for the format and the encoder's ratio check; licenses/ncompress-UNLICENSE.txt). Never throws.
--
-- local out, err = UnixCompress.decompress(buf, offset?, length?, { maxBytes = 2^28 }) -- a whole .Z file
-- local z = UnixCompress.compress(buf, offset?, length?, { maxBits = 16 }) -- -> a .Z file
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local UnixCompress = {}
export type DecodeOptions = { maxBytes: number? } -- refuse output larger than this (default 2^30)
export type EncodeOptions = { maxBits: number? } -- 9..16, default 16
local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift
local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
local MAXCODES = 65536
local CHECK_GAP = 10000
-- decoder tables (per call state lives in locals; the tables are reused: decode never yields)
local prefix = bcreate(MAXCODES * 4) -- u32: the code an entry extends
local suffix = bcreate(MAXCODES) -- u8: its last byte
local first = bcreate(MAXCODES) -- u8: its first byte
local length = bcreate(MAXCODES * 4) -- u32: its length
-- ------------------------------------------------------------------------------------------------ decode
-- decompress(buf, offset?, length?, opts?) -> buffer | nil, Err
function UnixCompress.decompress(buf: buffer | string, offset: number?, len: number?, opts: DecodeOptions?): (buffer?, Err.Err?)
local b, o, n, aerr = Bytes.span("UnixCompress.decompress", buf, offset, len)
if not b then
return nil, aerr
end
local maxBytes = (opts and opts.maxBytes) or 2 ^ 30
if n < 3 then
return nil, Err.new(Err.TRUNCATED, "header past the end", o)
end
if readu8(b, o) ~= 0x1F or readu8(b, o + 1) ~= 0x9D then
return nil, Err.new(Err.CORRUPT, "bad magic", o)
end
local flags = readu8(b, o + 2)
local maxbits = band(flags, 0x1F)
local block = band(flags, 0x80) ~= 0
if maxbits < 9 or maxbits > 16 then
return nil, Err.new(Err.UNSUPPORTED, "maximum code width " .. maxbits, o + 2)
end
if band(flags, 0x60) ~= 0 then
return nil, Err.new(Err.UNSUPPORTED, "reserved flag bits set", o + 2)
end
local maxmax = lshift(1, maxbits)
for i = 0, 255 do
writeu32(prefix, i * 4, 0)
writeu8(suffix, i, i)
writeu8(first, i, i)
writeu32(length, i * 4, 1)
end
local cap = math.min(math.max(n * 3, 1024), maxBytes)
local out = bcreate(cap)
local op = 0
local totalBits = (n - 3) * 8
local base = o + 3
local pos = 0 -- bit position from the first code
local gbase = 0 -- where the current group sequence starts
local nbits = 9
local mask = 511
local maxcode = 511
local freeEnt = if block then 257 else 256
local prev = -1
while pos + nbits <= totalBits do
if freeEnt > maxcode then
local g = nbits * 8
pos = gbase + (pos - gbase + g - 1) // g * g
gbase = pos
nbits += 1
maxcode = if nbits == maxbits then maxmax else lshift(1, nbits) - 1
mask = lshift(1, nbits) - 1
continue
end
-- the code: up to 23 bits from three bytes
local q = base + rshift(pos, 3)
local acc = readu8(b, q)
if q + 1 < o + n then
acc = bor(acc, lshift(readu8(b, q + 1), 8))
end
if q + 2 < o + n then
acc = bor(acc, lshift(readu8(b, q + 2), 16))
end
local c = band(rshift(acc, band(pos, 7)), mask)
pos += nbits
if c == 256 and block then
local g = nbits * 8
pos = gbase + (pos - gbase + g - 1) // g * g
gbase = pos
nbits = 9
mask = 511
maxcode = 511
freeEnt = 257
prev = -1
continue
end
local l
if prev < 0 then
if c >= 256 then
return nil, Err.new(Err.CORRUPT, "first code is not a literal", base + rshift(pos, 3))
end
l = 1
elseif c < freeEnt then
l = readu32(length, c * 4)
elseif c == freeEnt then
l = readu32(length, prev * 4) + 1
else
return nil, Err.new(Err.CORRUPT, "code past the table", base + rshift(pos, 3))
end
if op + l > cap then
if op + l > maxBytes then
return nil, Err.new(Err.LIMIT, "output over " .. maxBytes .. " bytes")
end
local ncap = math.min(math.max(cap * 2, op + l), maxBytes)
local nb = bcreate(ncap)
bcopy(nb, 0, out, 0, op)
out, cap = nb, ncap
end
-- the new entry (prev + first byte of c's string) before the copy: KwKwK reads it
if prev >= 0 and freeEnt < maxmax then
local f = if c == freeEnt then readu8(first, prev) else readu8(first, c)
writeu32(prefix, freeEnt * 4, prev)
writeu8(suffix, freeEnt, f)
writeu8(first, freeEnt, readu8(first, prev))
writeu32(length, freeEnt * 4, readu32(length, prev * 4) + 1)
freeEnt += 1
elseif prev >= 0 then
if c == freeEnt then
return nil, Err.new(Err.CORRUPT, "code past the table", base + rshift(pos, 3))
end
end
local p = op + l - 1
local k = c
while p >= op do
writeu8(out, p, readu8(suffix, k))
k = readu32(prefix, k * 4)
p -= 1
end
op += l
prev = c
end
local res = bcreate(op)
bcopy(res, 0, out, 0, op)
return res, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local HSIZE = 1 * 131072 -- open addressing over (prefix << 8 | byte) + 1 keys: twice the 65536 entries
local hkey = bcreate(HSIZE * 4)
local hval = bcreate(HSIZE * 4)
-- compress(buf, offset?, length?, opts?) -> a .Z file (block mode) | nil, Err
function UnixCompress.compress(buf: buffer | string, offset: number?, len: number?, opts: EncodeOptions?): (buffer?, Err.Err?)
local b, o, n, aerr = Bytes.span("UnixCompress.compress", buf, offset, len)
if not b then
return nil, aerr
end
local maxbits = (opts and opts.maxBits) or 16
if type(maxbits) ~= "number" or maxbits < 9 or maxbits > 16 or maxbits % 1 ~= 0 then
return nil, Err.new(Err.ARG, "maxBits must be 9..16")
end
-- at most 17 bits per input byte, plus group padding (< one group per width change / clear)
local cap = 3 + n * 2 + 64
local out = bcreate(cap)
writeu8(out, 0, 0x1F)
writeu8(out, 1, 0x9D)
writeu8(out, 2, bor(maxbits, 0x80))
local outbits = 24
local boff = 24
local acc, nb = 0, 0 -- pending bits not yet written (below 2^24)
local nbits = 9
local extcode = 513
local maxmax = lshift(1, maxbits)
local stcode = true
local freeEnt = 257
local ratio = 0
local checkpoint = CHECK_GAP
buffer.fill(hkey, 0, 0, HSIZE * 4)
local function put(code: number)
acc = bor(acc, lshift(code, nb))
nb += nbits
outbits += nbits
while nb >= 8 do
local q = rshift(outbits - nb, 3)
if q < cap then
writeu8(out, q, band(acc, 255))
end
acc = rshift(acc, 8)
nb -= 8
end
end
local function align()
-- round outbits up to a whole group of nbits-bit codes since boff; the skipped bits are zeros
local g = nbits * 8
local nbits2 = boff + (outbits - boff + g - 1) // g * g
if nb > 0 then
local q = rshift(outbits - nb, 3)
if q < cap then
writeu8(out, q, band(acc, 255))
end
end
acc, nb = 0, 0
outbits = nbits2
boff = nbits2
end
if n == 0 then
local res = bcreate(3)
bcopy(res, 0, out, 0, 3)
return res, nil
end
local ent = readu8(b, o)
local e = o + n
local i = o + 1
-- checks happen with a one-byte current string, right after an output (and at the start)
local function checks(consumed: number)
if freeEnt >= extcode then
if nbits < maxbits then
align()
nbits += 1
extcode = if nbits < maxbits then lshift(1, nbits) + 1 else lshift(1, nbits)
else
extcode = math.huge
stcode = false
end
end
if not stcode and consumed >= checkpoint then
checkpoint = consumed + CHECK_GAP
local outBytes = rshift(outbits, 3)
local rat
if consumed > 0x7FFFFF then
local d = rshift(outBytes, 8)
rat = if d == 0 then 0x7FFFFFFF else consumed // d
else
rat = (consumed * 256) // outBytes
end
if rat >= ratio then
ratio = rat
else
ratio = 0
buffer.fill(hkey, 0, 0, HSIZE * 4)
put(256)
align()
nbits = 9
extcode = 513
freeEnt = 257
stcode = true
end
end
end
checks(1)
while i < e do
local c = readu8(b, i)
i += 1
local key = ent * 256 + c + 1
local h = band(ent * 4099 + c * 131 + rshift(ent, 5), HSIZE - 1)
local found = -1
while true do
local k = readu32(hkey, h * 4)
if k == 0 then
break
elseif k == key then
found = readu32(hval, h * 4)
break
end
h = band(h + 1, HSIZE - 1)
end
if found >= 0 then
ent = found
else
put(ent)
if stcode then
writeu32(hkey, h * 4, key)
writeu32(hval, h * 4, freeEnt)
freeEnt += 1
end
ent = c
checks(i - o)
end
if rshift(outbits, 3) + 8 > cap then
-- grow (rare: only incompressible input passes 2 bytes per byte)
local ncap = cap * 2
local nbuf = bcreate(ncap)
bcopy(nbuf, 0, out, 0, cap)
out, cap = nbuf, ncap
end
end
put(ent)
if nb > 0 then
local q = rshift(outbits - nb, 3)
if q < cap then
writeu8(out, q, band(acc, 255))
end
end
local size = rshift(outbits + 7, 3)
local res = bcreate(size)
bcopy(res, 0, out, 0, math.min(size, cap))
return res, nil
end
-- isCompress(buf, offset?) -> true when the bytes at offset start a .Z file
function UnixCompress.isCompress(b: buffer, o: number?): boolean
local p = o or 0
return p + 3 <= blen(b) and readu8(b, p) == 0x1F and readu8(b, p + 1) == 0x9D
end
return UnixCompress
+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