formats-luau foundation: build (darklua + token passes) for Roblox and LuaJIT, compat prelude, core, Types, host adapters, API + registry, lint, tests on both runtimes; absorb deflate (codecs/Deflate + new compressor) and png (image/png + new encoder)

This commit is contained in:
4DBug committed 2026-10-31 08:18:01 -05:00
commit cdcb5b0b77
226 files changed
+8409

No files matched your search

+432
View File
@@ -0,0 +1,432 @@
--!strict
--!native
--!optimize 2
-- codecs/Deflate/Compress: a DEFLATE (RFC 1951) compressor. LZ77 over a 32 KB window with hash chains (chain depth
-- and lazy matching by level), then per block the cheapest of stored / fixed-Huffman / dynamic-Huffman (core/Huffman
-- length-limited codes). Level 0 = stored blocks only.
--
-- raw(buf, off, len, level) -> buffer. Never throws (the caller validated the arguments).
local Huffman = require("@formats/core/Huffman")
local readu8, writeu8, writeu16 = buffer.readu8, buffer.writeu8, buffer.writeu16
local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
local floor = math.floor
local WSIZE = 32768
local HSIZE = 65536
local MAXMATCH = 258
local BLOCKSYMS = 16384 -- symbols per block
-- per level (zlib's configuration_table): GOOD = a match this long quarters the chain for the lazy search, LAZY = no
-- lazy search after a match this long, NICE = stop searching at this length, CHAIN = max chain steps. Levels 1-3 are
-- greedy (no lazy matching).
local GOOD = { 4, 4, 4, 4, 8, 8, 8, 32, 32 }
local LAZY = { 0, 0, 0, 4, 16, 16, 32, 128, 258 }
local NICE = { 8, 16, 32, 16, 32, 128, 128, 258, 258 }
local CHAIN = { 4, 8, 32, 16, 32, 128, 256, 1024, 4096 }
-- length 3..258 -> code 257..285 (index len), its extra bits and base
local LCODE, LEXTRA, LBASEOF = table.create(259, 0), table.create(259, 0), table.create(259, 0)
local LBASE = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 }
local LEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }
for c = 1, 29 do
local base = LBASE[c]
local top = if c == 29 then 258 elseif c == 28 then 257 else LBASE[c + 1] - 1
for len = base, top do
LCODE[len] = 256 + c
LEXTRA[len] = LEXT[c]
LBASEOF[len] = base
end
end
local DBASE = {
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097,
6145, 8193, 12289, 16385, 24577,
}
local DEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }
-- distance -> code (0..29): direct for 1..256, by (d - 1) // 128 above
local DSMALL, DLARGE = table.create(257, 0), table.create(257, 0)
for c = 1, 30 do
local base = DBASE[c]
local top = if c == 30 then 32768 else DBASE[c + 1] - 1
for d = base, math.min(top, 256) do
DSMALL[d] = c - 1
end
if top > 256 then
for k = math.max(base, 257), top, 128 do
DLARGE[(k - 1) // 128 + 1] = c - 1
end
end
end
local function dcode(d: number): number
if d <= 256 then
return DSMALL[d]
end
return DLARGE[(d - 1) // 128 + 1]
end
local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }
-- fixed codes
local FIXLEN = table.create(288, 0)
for i = 1, 288 do
FIXLEN[i] = if i <= 144 then 8 elseif i <= 256 then 9 elseif i <= 280 then 7 else 8
end
local FIXDLEN = table.create(30, 5)
-- reversed (LSB-first) canonical codes for lengths
local function revCodes(lens: { number }): { number }
local codes = Huffman.codes(lens)
for i, l in lens do
if l > 0 then
codes[i] = Huffman.reverse(codes[i], l)
end
end
return codes
end
local FIXCODE = revCodes(FIXLEN)
local FIXDCODE = revCodes(FIXDLEN)
local POW = table.create(33, 0)
for i = 0, 32 do
POW[i + 1] = 2 ^ i
end
-- ------------------------------------------------------------------------------------------------ bit output
type Out = { buf: buffer, op: number, acc: number, cnt: number }
local function ensure(o: Out, n: number)
if o.op + n > blen(o.buf) then
local nb = bcreate(math.max(blen(o.buf) * 2, o.op + n))
bcopy(nb, 0, o.buf, 0, o.op)
o.buf = nb
end
end
-- put(v, n): n <= 24 bits, LSB first
local function put(o: Out, v: number, n: number)
local acc = o.acc + v * POW[o.cnt + 1]
local cnt = o.cnt + n
if cnt >= 8 then
ensure(o, 4)
local buf, op = o.buf, o.op
while cnt >= 8 do
local byte = acc % 256
writeu8(buf, op, byte)
op += 1
acc = (acc - byte) / 256
cnt -= 8
end
o.op = op
end
o.acc, o.cnt = acc, cnt
end
local function alignOut(o: Out)
if o.cnt > 0 then
put(o, 0, 8 - o.cnt)
end
end
-- ------------------------------------------------------------------------------------------------ blocks
-- syms: L[i] = literal 0..255 or 256 + match length; D[i] = distance (0 for literals)
local function storedBlock(o: Out, src: buffer, s: number, e: number, final: boolean)
local p = s
repeat
local n = math.min(65535, e - p)
local last = final and p + n >= e
put(o, if last then 1 else 0, 3)
alignOut(o)
ensure(o, 4 + n)
writeu16(o.buf, o.op, n)
writeu16(o.buf, o.op + 2, 65535 - n)
bcopy(o.buf, o.op + 4, src, p, n)
o.op += 4 + n
p += n
until p >= e
end
local function emitSymbols(o: Out, L: { number }, D: { number }, nsym: number, lcode: { number }, llen: { number }, dcodes: { number }, dlen: { number })
for i = 1, nsym do
local l = L[i]
if l < 256 then
put(o, lcode[l + 1], llen[l + 1])
else
local len = l - 256
local c = LCODE[len]
put(o, lcode[c + 1], llen[c + 1])
local xb = LEXTRA[len]
if xb > 0 then
put(o, len - LBASEOF[len], xb)
end
local d = D[i]
local dc = dcode(d)
put(o, dcodes[dc + 1], dlen[dc + 1])
xb = DEXT[dc + 1]
if xb > 0 then
put(o, d - DBASE[dc + 1], xb)
end
end
end
put(o, lcode[257], llen[257]) -- end of block
end
local function block(o: Out, src: buffer, s: number, e: number, L: { number }, D: { number }, nsym: number, final: boolean)
local lf = table.create(286, 0)
local df = table.create(30, 0)
local extra = 0
for i = 1, nsym do
local l = L[i]
if l < 256 then
lf[l + 1] += 1
else
local len = l - 256
lf[LCODE[len] + 1] += 1
extra += LEXTRA[len]
local dc = dcode(D[i])
df[dc + 1] += 1
extra += DEXT[dc + 1]
end
end
lf[257] = 1
local llen = Huffman.lengths(lf, 15)
local dlen = Huffman.lengths(df, 15)
local hlit = 286
while hlit > 257 and llen[hlit] == 0 do
hlit -= 1
end
local hdist = 30
while hdist > 1 and dlen[hdist] == 0 do
hdist -= 1
end
if dlen[1] == 0 and hdist == 1 then
dlen[1] = 1 -- at least one distance code (a lone 1-bit code, as zlib writes)
end
-- code-length symbols: RLE of the hlit + hdist lengths
local all = table.create(hlit + hdist, 0)
for i = 1, hlit do
all[i] = llen[i]
end
for i = 1, hdist do
all[hlit + i] = dlen[i]
end
local cs, cx = {}, {} -- symbol, extra value
local cf = table.create(19, 0)
local i = 1
local total = hlit + hdist
while i <= total do
local v = all[i]
local run = 1
while i + run <= total and all[i + run] == v do
run += 1
end
if v == 0 and run >= 3 then
local r = math.min(run, 138)
if r >= 11 then
table.insert(cs, 18)
table.insert(cx, r - 11)
cf[19] += 1
else
table.insert(cs, 17)
table.insert(cx, r - 3)
cf[18] += 1
end
i += r
elseif v ~= 0 and run >= 4 then
table.insert(cs, v)
table.insert(cx, 0)
cf[v + 1] += 1
local r = math.min(run - 1, 6)
table.insert(cs, 16)
table.insert(cx, r - 3)
cf[17] += 1
i += 1 + r
else
table.insert(cs, v)
table.insert(cx, 0)
cf[v + 1] += 1
i += 1
end
end
local clen = Huffman.lengths(cf, 7)
local hclen = 19
while hclen > 4 and clen[CLORDER[hclen] + 1] == 0 do
hclen -= 1
end
-- costs in bits
local dyn = 17 + 3 * hclen + extra
for k = 1, 19 do
dyn += cf[k] * clen[k]
end
dyn += cf[17] * 2 + cf[18] * 3 + cf[19] * 7
local fix = 3 + extra
for k = 1, 286 do
dyn += lf[k] * llen[k]
fix += lf[k] * FIXLEN[k]
end
for k = 1, 30 do
dyn += df[k] * dlen[k]
fix += df[k] * 5
end
local stored = (e - s) * 8 + 40 * (floor((e - s) / 65535) + 1) + 7
if stored <= dyn and stored <= fix then
storedBlock(o, src, s, e, final)
return
end
if fix <= dyn then
put(o, if final then 3 else 2, 3)
emitSymbols(o, L, D, nsym, FIXCODE, FIXLEN, FIXDCODE, FIXDLEN)
return
end
put(o, if final then 5 else 4, 3)
put(o, hlit - 257, 5)
put(o, hdist - 1, 5)
put(o, hclen - 4, 4)
for k = 1, hclen do
put(o, clen[CLORDER[k] + 1], 3)
end
local ccode = revCodes(clen)
for k = 1, #cs do
local c = cs[k]
put(o, ccode[c + 1], clen[c + 1])
if c == 16 then
put(o, cx[k], 2)
elseif c == 17 then
put(o, cx[k], 3)
elseif c == 18 then
put(o, cx[k], 7)
end
end
emitSymbols(o, L, D, nsym, revCodes(llen), llen, revCodes(dlen), dlen)
end
-- ------------------------------------------------------------------------------------------------ LZ77
local Compress = {}
function Compress.raw(src: buffer, off: number, len: number, level: number): buffer
local o: Out = { buf = bcreate(math.max(64, len // 2 + 64)), op = 0, acc = 0, cnt = 0 }
local e = off + len
if level == 0 or len == 0 then
if len == 0 then
put(o, 3, 3) -- one empty fixed block
put(o, 0, 7)
else
storedBlock(o, src, off, e, true)
end
alignOut(o)
local out = bcreate(o.op)
bcopy(out, 0, o.buf, 0, o.op)
return out
end
local maxChain = CHAIN[level]
local nice = NICE[level]
local good = GOOD[level]
local lazyMax = LAZY[level]
local head = table.create(HSIZE, -1)
local prev = table.create(WSIZE, -1)
local L = table.create(BLOCKSYMS, 0)
local D = table.create(BLOCKSYMS, 0)
local nsym = 0
local blockStart = off
local function hash(p: number): number
return ((readu8(src, p) * 251 + readu8(src, p + 1)) * 251 + readu8(src, p + 2)) % HSIZE
end
local function insert(p: number)
local h = hash(p) + 1
prev[p % WSIZE + 1] = head[h]
head[h] = p
end
-- longest match at p among earlier positions: len (0 if < 3), dist
local function find(p: number, steps: number): (number, number)
local maxLen = math.min(MAXMATCH, e - p)
if maxLen < 3 then
return 0, 0
end
local best, bestDist = 2, 0
local c = head[hash(p) + 1]
local limit = p - WSIZE
while c >= 0 and c > limit and steps > 0 do
if readu8(src, c + best) == readu8(src, p + best) and readu8(src, c) == readu8(src, p) then
local k = 1
while k < maxLen and readu8(src, c + k) == readu8(src, p + k) do
k += 1
end
if k > best then
best, bestDist = k, p - c
if k >= nice or k >= maxLen then
break
end
end
end
local nc = prev[c % WSIZE + 1]
if nc >= c then
break -- the slot was reused by a newer position: the chain ends here
end
c = nc
steps -= 1
end
if best < 3 then
return 0, 0
end
return best, bestDist
end
local function flush(upto: number, final: boolean)
block(o, src, blockStart, upto, L, D, nsym, final)
nsym = 0
blockStart = upto
end
local p = off
local stop3 = e - 3 -- positions with 3 bytes ahead can be hashed
while p < e do
local mlen, mdist = 0, 0
if p <= stop3 then
mlen, mdist = find(p, maxChain)
insert(p)
if mlen >= 3 and mlen < lazyMax and p + 1 <= stop3 then
local l2, d2 = find(p + 1, if mlen >= good then maxChain // 4 else maxChain)
if l2 > mlen then
-- a literal now, the longer match from p + 1
nsym += 1
L[nsym] = readu8(src, p)
D[nsym] = 0
p += 1
insert(p)
mlen, mdist = l2, d2
end
end
end
if mlen >= 3 then
nsym += 1
L[nsym] = 256 + mlen
D[nsym] = mdist
local q = p + 1
local qe = math.min(p + mlen, stop3 + 1)
while q < qe do
insert(q)
q += 1
end
p += mlen
else
nsym += 1
L[nsym] = readu8(src, p)
D[nsym] = 0
p += 1
end
if nsym >= BLOCKSYMS - 2 then
flush(p, p >= e)
end
end
if nsym > 0 or blockStart < e then
flush(e, true)
elseif blockStart == e and o.op == 0 and o.cnt == 0 then
put(o, 3, 3)
put(o, 0, 7)
end
alignOut(o)
local out = bcreate(o.op)
bcopy(out, 0, o.buf, 0, o.op)
return out
end
return Compress
+435
View File
@@ -0,0 +1,435 @@
--!strict
--!native
--!optimize 2
-- codecs/Deflate/Inflate: raw DEFLATE (RFC 1951) decoder: stored, fixed-Huffman and dynamic-Huffman blocks.
-- Absorbed from deflate-luau src/Deflate/Inflate.luau (same author); the table builder moved to core/Huffman, whose
-- entries are symbol * 32 + length (5 length bits instead of 4).
--
-- Bits are read LSB first into a 32-bit bit buffer (refilled 4 bytes at a time with one readu32 while the input
-- lasts). Huffman codes decode through a core/Huffman LSB table indexed by the next LITBITS / DISTBITS bits; a longer
-- code's primary slot links to a subtable, so a symbol is one or two table reads.
--
-- Nothing in this module throws on any input: every buffer read and write is bounds-checked, and corrupt data
-- returns nil, message. (Native code must never throw: it crashes Roblox Studio.)
local Huffman = require("@formats/core/Huffman")
local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32
local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len
local LITBITS, DISTBITS, CLBITS = 10, 8, 7
local LITMASK, DISTMASK, CLMASK = 1023, 255, 127
-- length codes 257..285 and distance codes 0..29: base value, extra bits
local LBASE = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 }
local LEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }
local DBASE = {
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097,
6145, 8193, 12289, 16385, 24577,
}
local DEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }
-- the order code-length code lengths are sent in
local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }
-- table capacities (entries): primary + one subtable per code longer than the primary width, worst case
local LITCAP = Huffman.capacity(288, LITBITS, 15)
local DISTCAP = Huffman.capacity(32, DISTBITS, 15)
local CLCAP = Huffman.capacity(19, CLBITS, 7)
-- fixed Huffman tables
local FLIT, FDIST = bcreate(LITCAP * 4), bcreate(DISTCAP * 4)
local FLITS, FDISTS
do
local l = bcreate(288)
bfill(l, 0, 8, 144)
bfill(l, 144, 9, 112)
bfill(l, 256, 7, 24)
bfill(l, 280, 8, 8)
FLITS = Huffman.buildLsb(l, 0, 288, FLIT, LITBITS)
local d = bcreate(30)
bfill(d, 0, 5, 30)
FDISTS = Huffman.buildLsb(d, 0, 30, FDIST, DISTBITS)
end
local Inflate = {}
-- Grow out (capacity cap) to hold at least need bytes. Returns the new buffer and capacity.
local function grow(out: buffer, op: number, need: number): (buffer, number)
local cap = math.max(blen(out) * 2, need, 1024)
local nb = bcreate(cap)
bcopy(nb, 0, out, 0, op)
return nb, cap
end
-- Inflate src[start, endpos) into a buffer. cap: initial output capacity; exact: true = the output must fit in
-- cap bytes (an error otherwise), false = grow as needed.
-- Returns out, outLen, consumedEnd (the input offset just past the final block) or nil, message.
function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean): (buffer?, any, number?)
local out = bcreate(cap)
local op = 0
local pos = start
local bitbuf, bitcnt, over = 0, 0, 0
local lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4)
local clt = bcreate(CLCAP * 4)
local lens = bcreate(320)
local final = 0
repeat
-- block header (3 bits); also up to 14 bits of a dynamic header
if bitcnt < 17 then
if pos + 4 <= endpos then
bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt))
local nb = rshift(32 - bitcnt, 3)
pos += nb
bitcnt += nb * 8
else
while bitcnt <= 24 do
if pos < endpos then
bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt))
pos += 1
else
over += 1
if over > 4 then
return nil, "truncated input"
end
end
bitcnt += 8
end
end
end
final = band(bitbuf, 1)
local btype = band(rshift(bitbuf, 1), 3)
bitbuf = rshift(bitbuf, 3)
bitcnt -= 3
if btype == 0 then
-- stored: skip to the byte boundary, give back the whole bytes still in the bit buffer
local k = band(bitcnt, 7)
bitcnt -= k
local real = rshift(bitcnt, 3) - over
if real < 0 then
return nil, "truncated input"
end
pos -= real
bitbuf, bitcnt, over = 0, 0, 0
if pos + 4 > endpos then
return nil, "truncated input"
end
local n = readu16(src, pos)
if n ~= bxor(readu16(src, pos + 2), 0xFFFF) then
return nil, "stored block length mismatch"
end
pos += 4
if pos + n > endpos then
return nil, "truncated input"
end
if op + n > cap then
if exact then
return nil, "output larger than expected"
end
out, cap = grow(out, op, op + n)
end
bcopy(out, op, src, pos, n)
op += n
pos += n
continue
end
local lsub, dsub
if btype == 1 then
lt, dt = FLIT, FDIST
lsub, dsub = FLITS, FDISTS
elseif btype == 2 then
if lt == FLIT then
lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4)
end
local hlit = band(bitbuf, 31) + 257
local hdist = band(rshift(bitbuf, 5), 31) + 1
local hclen = band(rshift(bitbuf, 10), 15) + 4
bitbuf = rshift(bitbuf, 14)
bitcnt -= 14
if hlit > 286 or hdist > 30 then
return nil, "too many length or distance symbols"
end
bfill(lens, 0, 0, 19)
for i = 1, hclen do
if bitcnt < 3 then
if pos + 4 <= endpos then
bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt))
local nb = rshift(32 - bitcnt, 3)
pos += nb
bitcnt += nb * 8
else
while bitcnt <= 24 do
if pos < endpos then
bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt))
pos += 1
else
over += 1
if over > 4 then
return nil, "truncated input"
end
end
bitcnt += 8
end
end
end
writeu8(lens, CLORDER[i], band(bitbuf, 7))
bitbuf = rshift(bitbuf, 3)
bitcnt -= 3
end
if Huffman.buildLsb(lens, 0, 19, clt, CLBITS) < 0 then
return nil, "invalid code lengths set"
end
local total = hlit + hdist
local i = 0
while i < total do
if bitcnt < 14 then
if pos + 4 <= endpos then
bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt))
local nb = rshift(32 - bitcnt, 3)
pos += nb
bitcnt += nb * 8
else
while bitcnt <= 24 do
if pos < endpos then
bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt))
pos += 1
else
over += 1
if over > 4 then
return nil, "truncated input"
end
end
bitcnt += 8
end
end
end
local e = readu32(clt, band(bitbuf, CLMASK) * 4)
local l = band(e, 31)
if l == 0 then
return nil, "invalid code lengths set"
end
bitbuf = rshift(bitbuf, l)
bitcnt -= l
local sym = rshift(e, 5)
if sym < 16 then
writeu8(lens, i, sym)
i += 1
else
local rep, val
if sym == 16 then
if i == 0 then
return nil, "repeat with no first length"
end
val = readu8(lens, i - 1)
rep = 3 + band(bitbuf, 3)
bitbuf = rshift(bitbuf, 2)
bitcnt -= 2
elseif sym == 17 then
val = 0
rep = 3 + band(bitbuf, 7)
bitbuf = rshift(bitbuf, 3)
bitcnt -= 3
else
val = 0
rep = 11 + band(bitbuf, 127)
bitbuf = rshift(bitbuf, 7)
bitcnt -= 7
end
if i + rep > total then
return nil, "too many code lengths"
end
bfill(lens, i, val, rep)
i += rep
end
end
if readu8(lens, 256) == 0 then
return nil, "missing end-of-block code"
end
lsub = Huffman.buildLsb(lens, 0, hlit, lt, LITBITS)
dsub = Huffman.buildLsb(lens, hlit, hdist, dt, DISTBITS)
if lsub < 0 or dsub < 0 then
return nil, "invalid literal/length or distance code set"
end
else
return nil, "invalid block type"
end
local lsmask = lshift(1, lsub) - 1
local dsmask = lshift(1, dsub) - 1
-- the symbol loop
while true do
if bitcnt < 15 then
if pos + 4 <= endpos then
bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt))
local nb = rshift(32 - bitcnt, 3)
pos += nb
bitcnt += nb * 8
else
while bitcnt <= 24 do
if pos < endpos then
bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt))
pos += 1
else
over += 1
if over > 4 then
return nil, "truncated input"
end
end
bitcnt += 8
end
end
end
local e = readu32(lt, band(bitbuf, LITMASK) * 4)
local l = band(e, 31)
if l == 0 then
if e == 0 then
return nil, "invalid literal/length code"
end
e = readu32(lt, (rshift(e, 5) + band(rshift(bitbuf, LITBITS), lsmask)) * 4)
l = band(e, 31)
if l == 0 then
return nil, "invalid literal/length code"
end
end
bitbuf = rshift(bitbuf, l)
bitcnt -= l
local sym = rshift(e, 5)
if sym < 256 then
if op >= cap then
if exact then
return nil, "output larger than expected"
end
out, cap = grow(out, op, op + 1)
end
writeu8(out, op, sym)
op += 1
elseif sym == 256 then
break
else
sym -= 256
if sym > 29 then
return nil, "invalid literal/length code"
end
-- up to 5 length extra bits + a 15-bit distance code
if bitcnt < 20 then
if pos + 4 <= endpos then
bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt))
local nb = rshift(32 - bitcnt, 3)
pos += nb
bitcnt += nb * 8
else
while bitcnt <= 24 do
if pos < endpos then
bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt))
pos += 1
else
over += 1
if over > 4 then
return nil, "truncated input"
end
end
bitcnt += 8
end
end
end
local len = LBASE[sym]
local xb = LEXT[sym]
if xb > 0 then
len += band(bitbuf, lshift(1, xb) - 1)
bitbuf = rshift(bitbuf, xb)
bitcnt -= xb
end
e = readu32(dt, band(bitbuf, DISTMASK) * 4)
l = band(e, 31)
if l == 0 then
if e == 0 then
return nil, "invalid distance code"
end
e = readu32(dt, (rshift(e, 5) + band(rshift(bitbuf, DISTBITS), dsmask)) * 4)
l = band(e, 31)
if l == 0 then
return nil, "invalid distance code"
end
end
bitbuf = rshift(bitbuf, l)
bitcnt -= l
local dsym = rshift(e, 5) + 1
if dsym > 30 then
return nil, "invalid distance code"
end
local dist = DBASE[dsym]
xb = DEXT[dsym]
if xb > 0 then
if bitcnt < 13 then
if pos + 4 <= endpos then
bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt))
local nb = rshift(32 - bitcnt, 3)
pos += nb
bitcnt += nb * 8
else
while bitcnt <= 24 do
if pos < endpos then
bitbuf = bor(bitbuf, lshift(readu8(src, pos), bitcnt))
pos += 1
else
over += 1
if over > 4 then
return nil, "truncated input"
end
end
bitcnt += 8
end
end
end
dist += band(bitbuf, lshift(1, xb) - 1)
bitbuf = rshift(bitbuf, xb)
bitcnt -= xb
end
if dist > op then
return nil, "invalid distance too far back"
end
if op + len > cap then
if exact then
return nil, "output larger than expected"
end
out, cap = grow(out, op, op + len)
end
local s = op - dist
if dist >= len then
if len <= 16 and op + 16 <= cap then
-- straight-line 16-byte copy (the bytes past len are rewritten later): no inner loop, which
-- keeps LuaJIT's traces simple; chunks read only bytes before op or already copied ones
writeu32(out, op, readu32(out, s))
writeu32(out, op + 4, readu32(out, s + 4))
writeu32(out, op + 8, readu32(out, s + 8))
writeu32(out, op + 12, readu32(out, s + 12))
elseif len <= 16 then
for k = 0, len - 1 do
writeu8(out, op + k, readu8(out, s + k))
end
else
bcopy(out, op, out, s, len)
end
op += len
elseif dist == 1 then
bfill(out, op, readu8(out, s), len)
op += len
else
-- overlapping: the pattern of period dist, copied in growing non-overlapping chunks
local rem = len
while rem > 0 do
local k = math.min(op - s, rem)
bcopy(out, op, out, s, k)
op += k
rem -= k
end
end
end
end
until final == 1
local consumed = pos + over - rshift(bitcnt, 3)
if consumed > endpos then
return nil, "truncated input"
end
return out, op, consumed
end
return Inflate
+301
View File
@@ -0,0 +1,301 @@
--!strict
-- codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
-- A codec (layer 1), not a format: png, zip, gzip, woff, tiff, ... build on it. Absorbed from deflate-luau 1.0.0
-- (same author; no third-party code); the compressor is new.
--
-- local Deflate = require("@formats/codecs/Deflate")
-- local out, err = Deflate.inflate(buf) -- raw deflate -> buffer, consumedEnd | nil, Err
-- local out, err = Deflate.inflate(buf, off, len, size) -- a range, with the exact output size if known
-- local out, err = Deflate.zlib(buf) -- checks the Adler-32
-- local out, err = Deflate.gunzip(buf) -- checks CRC-32 + ISIZE, concatenates members
-- local z = Deflate.compress(buf, { level = 6 }) -- raw deflate; also zlibCompress / gzip
--
-- Never throws: bad data and bad arguments return nil, Err (core/Err codes TRUNCATED / CORRUPT / CHECKSUM / ARG).
local Err = require("@formats/core/Err")
local Crc32 = require("@formats/core/Crc32")
local Adler32 = require("@formats/core/Adler32")
local Inflate = require("@formats/codecs/Deflate/Inflate")
local Compress = require("@formats/codecs/Deflate/Compress")
local Deflate = {}
Deflate.version = "1.1.0"
local function toBuffer(b: any): buffer?
if type(b) == "string" then
return buffer.fromstring(b)
end
if type(b) ~= "buffer" then
return nil
end
return b
end
-- (offset, length) clamped to the buffer; nil for non-numbers / negative / fractional / out-of-range offsets
local function range(b: buffer, off: number?, len: number?): (number?, number)
local n = buffer.len(b)
local o = off or 0
if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then
return nil, 0
end
local l = len or (n - o)
if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then
return nil, 0
end
if o + l > n then
l = n - o
end
return o, l
end
local function args(what: string, buf: any, offset: number?, length: number?): (buffer?, number, number, Err.Err?)
local b = toBuffer(buf)
if not b then
return nil, 0, 0, Err.new(Err.ARG, what .. ": expected a buffer or a string, got " .. typeof(buf))
end
local o, l = range(b, offset, length)
if not o then
return nil, 0, 0, Err.new(Err.ARG, what .. ": bad offset / length " .. tostring(offset) .. ", " .. tostring(length))
end
return b, o, l, nil
end
local function shrink(out: buffer, n: number): buffer
if buffer.len(out) == n then
return out
end
local b = buffer.create(n)
buffer.copy(b, 0, out, 0, n)
return b
end
local function inflateErr(msg: string, at: number?): Err.Err
local code = if string.find(msg, "truncated", 1, true) then Err.TRUNCATED else Err.CORRUPT
return Err.new(code, "inflate: " .. msg, at)
end
-- inflate(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err. Raw deflate.
-- expectedSize: the exact uncompressed size when known (a zip entry): the output is allocated once, and a stream
-- that inflates to a different size is an error. consumedEnd is the input offset just past the final block.
function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, expectedSize: number?): (buffer?, any)
local b, o, l, aerr = args("Deflate.inflate", buf, offset, length)
if not b then
return nil, aerr
end
local exact = expectedSize ~= nil
local cap
if exact then
if type(expectedSize) ~= "number" or expectedSize < 0 or expectedSize % 1 ~= 0 then
return nil, Err.new(Err.ARG, "Deflate.inflate: bad expectedSize " .. tostring(expectedSize))
end
cap = expectedSize
else
cap = math.max(1024, l * 4)
end
local out, n, consumed = Inflate.raw(b, o, o + l, cap :: number, exact)
if not out then
return nil, inflateErr(tostring(n), o)
end
if exact and n ~= expectedSize then
return nil, Err.new(Err.CORRUPT, string.format("inflate: output is %d bytes, expected %d", n, expectedSize :: number))
end
return shrink(out, n), consumed
end
-- zlib(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err
function Deflate.zlib(buf: buffer | string, offset: number?, length: number?, expectedSize: number?): (buffer?, any)
local b, o, l, aerr = args("Deflate.zlib", buf, offset, length)
if not b then
return nil, aerr
end
if l < 6 then
return nil, Err.new(Err.TRUNCATED, "zlib: truncated header", o)
end
local cmf, flg = buffer.readu8(b, o), buffer.readu8(b, o + 1)
if cmf % 16 ~= 8 or cmf // 16 > 7 then
return nil, Err.new(Err.CORRUPT, "zlib: not a deflate stream (CMF " .. cmf .. ")", o)
end
if (cmf * 256 + flg) % 31 ~= 0 then
return nil, Err.new(Err.CORRUPT, "zlib: header check failed", o)
end
if bit32.band(flg, 0x20) ~= 0 then
return nil, Err.new(Err.UNSUPPORTED, "zlib: preset dictionaries are not supported", o)
end
local out, consumed = Deflate.inflate(b, o + 2, l - 2, expectedSize)
if not out then
return nil, consumed
end
if consumed + 4 > o + l then
return nil, Err.new(Err.TRUNCATED, "zlib: missing Adler-32", consumed)
end
local want = bit32.byteswap(buffer.readu32(b, consumed))
local got = Adler32.raw(out, 0, buffer.len(out))
if got ~= want then
return nil, Err.new(Err.CHECKSUM, string.format("zlib: Adler-32 mismatch (%08x, expected %08x)", got, want), consumed)
end
return out, consumed + 4
end
-- gunzip(buf, offset?, length?) -> buffer | nil, Err. Members are concatenated; trailing data after a member that is
-- not another gzip member (zero padding, garbage) is ignored, as gzip -d does.
function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?)
local b, o, l, aerr = args("Deflate.gunzip", buf, offset, length)
if not b then
return nil, aerr
end
local e = o + l
local parts, total = {}, 0
local p = o
repeat
if p + 18 > e then
if #parts > 0 then
break
end
return nil, Err.new(Err.TRUNCATED, "gzip: truncated member", p)
end
if buffer.readu8(b, p) ~= 0x1f or buffer.readu8(b, p + 1) ~= 0x8b then
if #parts > 0 then
break -- trailing garbage after a member: ignored, as gzip -d does
end
return nil, Err.new(Err.CORRUPT, "gzip: bad magic", p)
end
if buffer.readu8(b, p + 2) ~= 8 then
return nil, Err.new(Err.UNSUPPORTED, "gzip: unknown compression method", p + 2)
end
local flg = buffer.readu8(b, p + 3)
if flg >= 0x20 then
return nil, Err.new(Err.CORRUPT, "gzip: reserved flags set", p + 3)
end
local q = p + 10
if bit32.band(flg, 4) ~= 0 then -- FEXTRA
if q + 2 > e then
return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q)
end
q += 2 + buffer.readu16(b, q)
end
for _, bit in { 8, 16 } do -- FNAME, FCOMMENT: zero-terminated
if bit32.band(flg, bit) ~= 0 then
while q < e and buffer.readu8(b, q) ~= 0 do
q += 1
end
q += 1
end
end
if bit32.band(flg, 2) ~= 0 then -- FHCRC
q += 2
end
if q >= e then
return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q)
end
local out, consumed = Deflate.inflate(b, q, e - q)
if not out then
return nil, consumed
end
if consumed + 8 > e then
return nil, Err.new(Err.TRUNCATED, "gzip: missing trailer", consumed)
end
local want, isize = buffer.readu32(b, consumed), buffer.readu32(b, consumed + 4)
local got = Crc32.raw(out, 0, buffer.len(out))
if got ~= want then
return nil, Err.new(Err.CHECKSUM, string.format("gzip: CRC-32 mismatch (%08x, expected %08x)", got, want), consumed)
end
if buffer.len(out) % 4294967296 ~= isize then
return nil, Err.new(Err.CORRUPT, "gzip: length mismatch", consumed + 4)
end
table.insert(parts, out)
total += buffer.len(out)
p = consumed + 8
-- skip zero padding
local z = p
while z < e and buffer.readu8(b, z) == 0 do
z += 1
end
if z == e then
break
end
until p >= e
if #parts == 1 then
return parts[1], nil
end
local res = buffer.create(total)
local w = 0
for _, part in parts do
buffer.copy(res, w, part)
w += buffer.len(part)
end
return res, nil
end
export type CompressOptions = {
level: number?, -- 0 (stored) .. 9 (best); default 6
}
local function level(opts: CompressOptions?): number?
local lv = if opts and opts.level ~= nil then opts.level else 6
if type(lv) ~= "number" or lv < 0 or lv > 9 or lv % 1 ~= 0 then
return nil
end
return lv
end
-- compress(buf, opts?) -> raw deflate buffer | nil, Err
function Deflate.compress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?)
local b = toBuffer(buf)
local lv = level(opts)
if not b or not lv then
return nil, Err.new(Err.ARG, "Deflate.compress: expected a buffer or a string and opts.level 0..9")
end
return Compress.raw(b, 0, buffer.len(b), lv), nil
end
-- zlibCompress(buf, opts?) -> zlib stream | nil, Err
function Deflate.zlibCompress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?)
local b = toBuffer(buf)
local lv = level(opts)
if not b or not lv then
return nil, Err.new(Err.ARG, "Deflate.zlibCompress: expected a buffer or a string and opts.level 0..9")
end
local raw = Compress.raw(b, 0, buffer.len(b), lv)
local n = buffer.len(raw)
local out = buffer.create(n + 6)
local flevel = if lv < 2 then 0 elseif lv < 6 then 1 elseif lv == 6 then 2 else 3
local cmf = 0x78
local flg = flevel * 64
flg += 31 - (cmf * 256 + flg) % 31
buffer.writeu8(out, 0, cmf)
buffer.writeu8(out, 1, flg)
buffer.copy(out, 2, raw, 0, n)
buffer.writeu32(out, n + 2, bit32.byteswap(Adler32.raw(b, 0, buffer.len(b))))
return out, nil
end
-- gzip(buf, opts?) -> gzip member (no name, mtime 0) | nil, Err
function Deflate.gzip(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?)
local b = toBuffer(buf)
local lv = level(opts)
if not b or not lv then
return nil, Err.new(Err.ARG, "Deflate.gzip: expected a buffer or a string and opts.level 0..9")
end
local raw = Compress.raw(b, 0, buffer.len(b), lv)
local n = buffer.len(raw)
local out = buffer.create(n + 18)
buffer.writestring(out, 0, "\31\139\8\0\0\0\0\0")
buffer.writeu8(out, 8, if lv >= 9 then 2 elseif lv <= 1 then 4 else 0)
buffer.writeu8(out, 9, 255)
buffer.copy(out, 10, raw, 0, n)
buffer.writeu32(out, n + 10, Crc32.raw(b, 0, buffer.len(b)))
buffer.writeu32(out, n + 14, buffer.len(b) % 4294967296)
return out, nil
end
-- crc32 / adler32 (kept from deflate-luau's API; the same as core/Crc32.of / core/Adler32.of)
Deflate.crc32 = function(buf: buffer | string, offset: number?, length: number?, crc: number?): number
local b = toBuffer(buf) or buffer.create(0)
return Crc32.of(b, offset, length, crc)
end
Deflate.adler32 = function(buf: buffer | string, offset: number?, length: number?, adler: number?): number
local b = toBuffer(buf) or buffer.create(0)
return Adler32.of(b, offset, length, adler)
end
return Deflate