Files
rosetta/src/Formats/codecs/Zstd/Decode.luau
T

981 lines
27 KiB
Luau

--!strict
--!native
--!optimize 2
-- codecs/Zstd/Decode: Zstandard frame decoder (RFC 8878), written from the specification (no code copied from the
-- BSD reference implementation). Frames (any number, concatenated), skippable frames, raw / RLE / compressed blocks,
-- Huffman literals (1 or 4 streams, new or repeated table), FSE sequence tables (predefined / RLE / compressed /
-- repeat), repeat offsets, the XXH64 content checksum. Not supported: dictionaries (a non-zero dictionary ID).
--
-- The whole output lives in one buffer, so the window is the output itself (offsets are checked against the frame's
-- start). Backward bitstreams are read through bit offsets: bits [o - n, o) of a stream come from one readu32 at
-- byte (o - n) / 8, bits before the stream start read as zeros.
--
-- Nothing here throws on any input: every read is bounds-checked; failures return nil, code, message, offset.
local Xxh64 = require("@formats/codecs/Zstd/Xxh64")
local band, lshift, rshift = bit32.band, bit32.lshift, bit32.rshift
local readu8, readu16, readu32, writeu8, writeu16, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32
local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len
local MAGIC = 0xFD2FB528
local BLOCK_MAX = 131072
local Decode = {}
-- ------------------------------------------------------------------------------------------------ tables
-- literal length / match length codes: baseline, extra bits (index = code + 1)
local LL_BASE = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 24, 28, 32, 40, 48, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536 }
local LL_BITS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }
local ML_BASE = {
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35, 37, 39, 41, 43, 47, 51, 59, 67, 83, 99, 131, 259, 515, 1027, 2051, 4099, 8195, 16387, 32771, 65539,
}
local ML_BITS = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
}
local LL_DEFAULT = { 4, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 1, -1, -1, -1, -1 }
local ML_DEFAULT = {
1, 4, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1,
}
local OF_DEFAULT = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1 }
-- highest set bit of 1..2048
local HB = table.create(2048, 0)
do
local v = 0
for i = 1, 2048 do
if i >= lshift(2, v) then
v += 1
end
HB[i] = v
end
end
-- ------------------------------------------------------------------------------------------------ bit readers
-- backward stream starting at byte s: bits [o - n, o) (n <= 25), bits below 0 are zeros
local function peek(b: buffer, s: number, o: number, n: number): number
if n <= 0 then
return 0
end
local lo = o - n
if lo >= 0 then
local byte = s + rshift(lo, 3)
local bl = blen(b)
if byte + 4 <= bl then
return band(rshift(readu32(b, byte), band(lo, 7)), lshift(1, n) - 1)
end
local v = 0
local m = 1
for k = 0, 3 do
if byte + k < bl then
v += readu8(b, byte + k) * m
end
m *= 256
end
return band(rshift(v, band(lo, 7)), lshift(1, n) - 1)
end
if o <= 0 then
return 0
end
return lshift(peek(b, s, o, o), -lo)
end
-- the bit length of a backward stream [s, e) (up to its end marker), or -1 when the last byte is 0 / it is empty
local function streamBits(b: buffer, s: number, e: number): number
if e <= s then
return -1
end
local last = readu8(b, e - 1)
if last == 0 then
return -1
end
return (e - 1 - s) * 8 + HB[last]
end
-- forward stream: n (<= 24) bits at bit position bp from byte p; bytes at or past e read as zeros
local function getF(b: buffer, p: number, e: number, bp: number, n: number): number
local byte = p + rshift(bp, 3)
local v = 0
local m = 1
for k = 0, 3 do
if byte + k < e then
v += readu8(b, byte + k) * m
end
m *= 256
end
return band(rshift(v, band(bp, 7)), lshift(1, n) - 1)
end
-- ------------------------------------------------------------------------------------------------ FSE
-- FSE decoding table entries (u32): symbol | nbBits << 8 | newStateBase << 16
local symTmp = bcreate(512)
-- build(norm, nsym, al, t) -> true | nil, message. norm: { [symbol + 1] = normalized count (-1 = "less than 1") }
local function buildFse(norm: { number }, nsym: number, al: number, t: buffer): (boolean?, string?)
local size = lshift(1, al)
local high = size - 1
local next = table.create(nsym, 0)
for s = 0, nsym - 1 do
local c = norm[s + 1]
if c == -1 then
if high < 0 then
return nil, "bad FSE distribution"
end
writeu8(symTmp, high, s)
high -= 1
next[s + 1] = 1
else
next[s + 1] = c
end
end
local pos = 0
local step = rshift(size, 1) + rshift(size, 3) + 3
local mask = size - 1
for s = 0, nsym - 1 do
local c = norm[s + 1]
for _ = 1, c do
writeu8(symTmp, pos, s)
local guard = 0
repeat
pos = band(pos + step, mask)
guard += 1
until pos <= high or guard > size
if guard > size then
return nil, "bad FSE distribution"
end
end
end
if pos ~= 0 then
return nil, "bad FSE distribution"
end
for u = 0, size - 1 do
local s = readu8(symTmp, u)
local ns = next[s + 1]
if ns < 1 or ns > 2048 then
return nil, "bad FSE distribution"
end
next[s + 1] = ns + 1
local nb = al - HB[ns]
if nb < 0 then
return nil, "bad FSE distribution"
end
writeu32(t, u * 4, s + nb * 256 + (lshift(ns, nb) - size) * 65536)
end
return true, nil
end
-- ncount(b, p, e, maxSym, maxAL, norm) -> al, bytesUsed, nsym | nil, message: an FSE table description
local function ncount(b: buffer, p: number, e: number, maxSym: number, maxAL: number, norm: { number }): (number?, any, number?)
if p >= e then
return nil, "truncated FSE table"
end
local al = getF(b, p, e, 0, 4) + 5
if al > maxAL then
return nil, "FSE accuracy log too large"
end
local bp = 4
local remaining = lshift(1, al) + 1
local threshold = lshift(1, al)
local nbBits = al + 1
local sym = 0
local prev0 = false
while remaining > 1 and sym <= maxSym do
if prev0 then
local n0 = sym
while true do
local v = getF(b, p, e, bp, 2)
bp += 2
if v == 3 then
n0 += 3
if n0 > maxSym or bp > (e - p) * 8 then
return nil, "bad FSE table"
end
else
n0 += v
break
end
end
if n0 > maxSym then
return nil, "bad FSE table"
end
while sym < n0 do
norm[sym + 1] = 0
sym += 1
end
end
local max = 2 * threshold - 1 - remaining
local count
local low = getF(b, p, e, bp, nbBits - 1)
if low < max then
count = low
bp += nbBits - 1
else
count = getF(b, p, e, bp, nbBits)
if count >= threshold then
count -= max
end
bp += nbBits
end
count -= 1
remaining -= if count < 0 then -count else count
if remaining < 1 then
return nil, "bad FSE table"
end
norm[sym + 1] = count
sym += 1
prev0 = count == 0
while remaining < threshold do
nbBits -= 1
threshold = rshift(threshold, 1)
end
end
if remaining ~= 1 then
return nil, "bad FSE table"
end
local used = rshift(bp + 7, 3)
if p + used > e then
return nil, "truncated FSE table"
end
for s = sym, maxSym do
norm[s + 1] = 0
end
return al, used, sym
end
local function predefined(dist: { number }, al: number): buffer
local t = bcreate(lshift(1, al) * 4)
buildFse(dist, #dist, al, t)
return t
end
local LL_PRE, ML_PRE, OF_PRE = predefined(LL_DEFAULT, 6), predefined(ML_DEFAULT, 6), predefined(OF_DEFAULT, 5)
-- ------------------------------------------------------------------------------------------------ Huffman
-- hufTable(b, p, e, st) -> bytesUsed | nil, message: a Huffman tree description into st.huf (u16: sym | nbBits << 8)
local weights = bcreate(256)
local wfse = bcreate(64 * 4)
local function hufTable(b: buffer, p: number, e: number, st: any): (number?, string?)
if p >= e then
return nil, "truncated Huffman table"
end
local hdr = readu8(b, p)
local n = 0
local used
if hdr >= 128 then
n = hdr - 127
used = 1 + rshift(n + 1, 1)
if p + used > e then
return nil, "truncated Huffman table"
end
for i = 0, n - 1 do
local byte = readu8(b, p + 1 + rshift(i, 1))
writeu8(weights, i, if band(i, 1) == 0 then rshift(byte, 4) else band(byte, 15))
end
else
used = 1 + hdr
if p + used > e then
return nil, "truncated Huffman table"
end
local q, qe = p + 1, p + 1 + hdr
local norm = st.norm
local al, nb = ncount(b, q, qe, 255, 6, norm)
if not al then
return nil, nb
end
local ok, msg = buildFse(norm, 256, al, wfse)
if not ok then
return nil, msg
end
local ss = q + nb
local off = streamBits(b, ss, qe)
if off < 0 then
return nil, "bad Huffman weight stream"
end
local s1 = peek(b, ss, off, al)
off -= al
local s2 = peek(b, ss, off, al)
off -= al
while true do
if n > 254 then
return nil, "too many Huffman weights"
end
local e1 = readu32(wfse, s1 * 4)
writeu8(weights, n, band(e1, 255))
n += 1
local k = band(rshift(e1, 8), 255)
s1 = rshift(e1, 16) + peek(b, ss, off, k)
off -= k
if off < 0 then
writeu8(weights, n, band(readu32(wfse, s2 * 4), 255))
n += 1
break
end
local e2 = readu32(wfse, s2 * 4)
writeu8(weights, n, band(e2, 255))
n += 1
k = band(rshift(e2, 8), 255)
s2 = rshift(e2, 16) + peek(b, ss, off, k)
off -= k
if off < 0 then
writeu8(weights, n, band(readu32(wfse, s1 * 4), 255))
n += 1
break
end
end
end
-- the last weight is implied: the total must reach the next power of two
local total = 0
for i = 0, n - 1 do
local w = readu8(weights, i)
if w > 11 then
return nil, "bad Huffman weight"
end
if w > 0 then
total += lshift(1, w - 1)
end
end
if total == 0 or total >= 2048 then
return nil, "bad Huffman weights"
end
local maxBits = HB[total] + 1
local rest = lshift(1, maxBits) - total
if band(rest, rest - 1) ~= 0 then
return nil, "bad Huffman weights"
end
writeu8(weights, n, HB[rest] + 1)
local nsym = n + 1
-- codes: the longest first, in symbol order within a length
local rankCount = table.create(13, 0)
for i = 0, nsym - 1 do
local w = readu8(weights, i)
if w > 0 then
local bits = maxBits + 1 - w
rankCount[bits + 1] += 1
end
end
local rankIdx = table.create(13, 0)
rankIdx[maxBits + 1] = 0
for i = maxBits, 1, -1 do
rankIdx[i] = rankIdx[i + 1] + rankCount[i + 1] * lshift(1, maxBits - i)
end
if rankIdx[1] ~= lshift(1, maxBits) then
return nil, "bad Huffman weights"
end
local t = st.huf
for i = 0, nsym - 1 do
local w = readu8(weights, i)
if w > 0 then
local bits = maxBits + 1 - w
local code = rankIdx[bits + 1]
local len = lshift(1, maxBits - bits)
local v = i + bits * 256
for k = code, code + len - 1 do
writeu16(t, k * 2, v)
end
rankIdx[bits + 1] = code + len
end
end
st.hufBits = maxBits
return used, nil
end
-- one Huffman stream [s, e) -> cnt literals at lit[dp] | nil, message
local function hufStream(b: buffer, s: number, e: number, t: buffer, mb: number, lit: buffer, dp: number, cnt: number): string?
local off = streamBits(b, s, e)
if off < 0 then
return "bad Huffman stream"
end
local mmask = lshift(1, mb) - 1
local fastEnd = blen(b) - 4
for k = dp, dp + cnt - 1 do
local lo = off - mb
local idx
if lo >= 0 then
local byte = s + rshift(lo, 3)
if byte <= fastEnd then
idx = band(rshift(readu32(b, byte), band(lo, 7)), mmask)
else
idx = peek(b, s, off, mb)
end
else
idx = peek(b, s, off, mb)
end
local v = readu16(t, idx * 2)
writeu8(lit, k, v)
off -= rshift(v, 8)
end
if off ~= 0 then
return "Huffman stream size mismatch"
end
return nil
end
-- ------------------------------------------------------------------------------------------------ frames
-- grow st.out to hold need bytes (doubling, capped at st.maxBytes): true | false (over the limit)
local function grow(st: any, need: number): boolean
if need > st.maxBytes then
return false
end
local cap = math.min(st.maxBytes, math.max(blen(st.out) * 2, need, 65536))
local nb = bcreate(cap)
bcopy(nb, 0, st.out, 0, st.op)
st.out = nb
return true
end
-- a compressed block [p, e): nil (ok) | code, message
local function block(b: buffer, p: number, e: number, st: any): (string?, string?)
-- literals section
local b0 = readu8(b, p)
local ltype = band(b0, 3)
local sf = band(rshift(b0, 2), 3)
local regen
local litSrc, litPos
local lit = st.lit
if ltype <= 1 then
if sf == 0 or sf == 2 then
regen = rshift(b0, 3)
p += 1
elseif sf == 1 then
if p + 2 > e then
return "TRUNCATED", "truncated literals header"
end
regen = rshift(b0, 4) + readu8(b, p + 1) * 16
p += 2
else
if p + 3 > e then
return "TRUNCATED", "truncated literals header"
end
regen = rshift(b0, 4) + readu8(b, p + 1) * 16 + readu8(b, p + 2) * 4096
p += 3
end
if regen > BLOCK_MAX then
return "CORRUPT", "literals too large"
end
if ltype == 0 then
if p + regen > e then
return "TRUNCATED", "truncated raw literals"
end
litSrc, litPos = b, p
p += regen
else
if p + 1 > e then
return "TRUNCATED", "truncated RLE literals"
end
bfill(lit, 0, readu8(b, p), regen)
litSrc, litPos = lit, 0
p += 1
end
else
local csize
if sf <= 1 then
if p + 3 > e then
return "TRUNCATED", "truncated literals header"
end
local v = b0 + readu8(b, p + 1) * 256 + readu8(b, p + 2) * 65536
regen = band(rshift(v, 4), 0x3FF)
csize = band(rshift(v, 14), 0x3FF)
p += 3
elseif sf == 2 then
if p + 4 > e then
return "TRUNCATED", "truncated literals header"
end
local v = readu32(b, p)
regen = band(rshift(v, 4), 0x3FFF)
csize = rshift(v, 18)
p += 4
else
if p + 5 > e then
return "TRUNCATED", "truncated literals header"
end
local v = readu32(b, p)
regen = band(rshift(v, 4), 0x3FFFF)
csize = rshift(v, 22) + readu8(b, p + 4) * 1024
p += 5
end
if regen > BLOCK_MAX then
return "CORRUPT", "literals too large"
end
if p + csize > e then
return "TRUNCATED", "truncated compressed literals"
end
local hs, he = p, p + csize
p = he
if ltype == 2 then
local used, herr = hufTable(b, hs, he, st)
if not used then
return "CORRUPT", herr
end
hs += used
elseif not st.hufBits then
return "CORRUPT", "treeless literals without a previous Huffman table"
end
local t, mb = st.huf, st.hufBits
if sf == 0 then
local herr = hufStream(b, hs, he, t, mb, lit, 0, regen)
if herr then
return "CORRUPT", herr
end
else
if hs + 6 > he then
return "CORRUPT", "truncated jump table"
end
local l1, l2, l3 = readu16(b, hs), readu16(b, hs + 2), readu16(b, hs + 4)
local s1 = hs + 6
local s2 = s1 + l1
local s3 = s2 + l2
local s4 = s3 + l3
if s4 > he then
return "CORRUPT", "bad jump table"
end
local seg = rshift(regen + 3, 2)
local last = regen - 3 * seg
if last < 0 then
return "CORRUPT", "bad 4-stream literals size"
end
local herr = hufStream(b, s1, s2, t, mb, lit, 0, seg)
or hufStream(b, s2, s3, t, mb, lit, seg, seg)
or hufStream(b, s3, s4, t, mb, lit, 2 * seg, seg)
or hufStream(b, s4, he, t, mb, lit, 3 * seg, last)
if herr then
return "CORRUPT", herr
end
end
litSrc, litPos = lit, 0
end
-- sequences section header
if p >= e then
return "TRUNCATED", "missing sequences header"
end
local nbSeq = readu8(b, p)
p += 1
if nbSeq >= 128 then
if nbSeq == 255 then
if p + 2 > e then
return "TRUNCATED", "truncated sequences header"
end
nbSeq = readu16(b, p) + 0x7F00
p += 2
else
if p + 1 > e then
return "TRUNCATED", "truncated sequences header"
end
nbSeq = (nbSeq - 128) * 256 + readu8(b, p)
p += 1
end
end
local op = st.op
if nbSeq == 0 then
if p ~= e then
return "CORRUPT", "data after an empty sequences section"
end
if op + regen > blen(st.out) then
if not grow(st, op + regen) then
return "LIMIT", "output over the size limit"
end
end
bcopy(st.out, op, litSrc, litPos, regen)
st.op = op + regen
return nil, nil
end
if p >= e then
return "TRUNCATED", "missing compression modes"
end
local modes = readu8(b, p)
p += 1
if band(modes, 3) ~= 0 then
return "CORRUPT", "reserved bits set in compression modes"
end
-- the three tables, in the order LL, OF, ML
local tabs = st.tabs
for k = 1, 3 do
local mode = band(rshift(modes, 8 - 2 * k), 3)
local maxSym = if k == 1 then 35 elseif k == 2 then 31 else 52
local maxAL = if k == 1 then 9 elseif k == 2 then 8 else 9
if mode == 0 then
tabs[k] = if k == 1 then LL_PRE elseif k == 2 then OF_PRE else ML_PRE
tabs[k + 3] = if k == 2 then 5 else 6
elseif mode == 1 then
if p >= e then
return "TRUNCATED", "truncated RLE table"
end
local sym = readu8(b, p)
p += 1
if sym > maxSym then
return "CORRUPT", "bad RLE symbol"
end
local t = st.rle[k]
writeu32(t, 0, sym)
tabs[k] = t
tabs[k + 3] = 0
elseif mode == 2 then
local norm = st.norm
local al, used, nsym = ncount(b, p, e, maxSym, maxAL, norm)
if not al then
return "CORRUPT", used
end
p += used
local t = st.dyn[k]
local ok, msg = buildFse(norm, nsym :: number, al, t)
if not ok then
return "CORRUPT", msg
end
tabs[k] = t
tabs[k + 3] = al
else
if not tabs[k] then
return "CORRUPT", "repeated table without a previous one"
end
end
end
local llT, ofT, mlT = tabs[1] :: buffer, tabs[2] :: buffer, tabs[3] :: buffer
local llAL, ofAL, mlAL = tabs[4] :: number, tabs[5] :: number, tabs[6] :: number
-- the sequences bitstream
local s = p
local off = streamBits(b, s, e)
if off < 0 then
return "CORRUPT", "bad sequences bitstream"
end
local llS = peek(b, s, off, llAL)
off -= llAL
local ofS = peek(b, s, off, ofAL)
off -= ofAL
local mlS = peek(b, s, off, mlAL)
off -= mlAL
local rep1, rep2, rep3 = st.rep1, st.rep2, st.rep3
local out = st.out
local cap = blen(out)
local frameStart = st.frameStart
local lp, litEnd = litPos, litPos + regen
local fastEnd = blen(b) - 4
for i = 1, nbSeq do
local ofE, llE, mlE = readu32(ofT, ofS * 4), readu32(llT, llS * 4), readu32(mlT, mlS * 4)
local ofCode = band(ofE, 255)
local mlCode = band(mlE, 255) + 1
local llCode = band(llE, 255) + 1
-- offset bits, then match length bits, then literal length bits
local ofv
if ofCode > 24 then
local hiN = ofCode - 24
local hi = peek(b, s, off, hiN)
off -= hiN
ofv = lshift(1, ofCode) + hi * 16777216 + peek(b, s, off, 24)
off -= 24
elseif ofCode > 0 then
local lo = off - ofCode
local v
if lo >= 0 and s + rshift(lo, 3) <= fastEnd then
v = band(rshift(readu32(b, s + rshift(lo, 3)), band(lo, 7)), lshift(1, ofCode) - 1)
else
v = peek(b, s, off, ofCode)
end
off = lo
ofv = lshift(1, ofCode) + v
else
ofv = 1
end
local ml = ML_BASE[mlCode]
local nb = ML_BITS[mlCode]
if nb > 0 then
ml += peek(b, s, off, nb)
off -= nb
end
local ll = LL_BASE[llCode]
nb = LL_BITS[llCode]
if nb > 0 then
ll += peek(b, s, off, nb)
off -= nb
end
-- repeat offsets
local offset
if ofv > 3 then
offset = ofv - 3
rep3 = rep2
rep2 = rep1
rep1 = offset
else
local idx = ofv - 1
if ll == 0 then
idx += 1
end
if idx == 0 then
offset = rep1
else
if idx == 1 then
offset = rep2
elseif idx == 2 then
offset = rep3
else
offset = rep1 - 1
end
if idx > 1 then
rep3 = rep2
end
rep2 = rep1
rep1 = offset
end
end
-- state updates (not after the last sequence): LL, ML, OF
if i < nbSeq then
nb = band(rshift(llE, 8), 255)
llS = rshift(llE, 16) + peek(b, s, off, nb)
off -= nb
nb = band(rshift(mlE, 8), 255)
mlS = rshift(mlE, 16) + peek(b, s, off, nb)
off -= nb
nb = band(rshift(ofE, 8), 255)
ofS = rshift(ofE, 16) + peek(b, s, off, nb)
off -= nb
end
-- execute
if lp + ll > litEnd then
return "CORRUPT", "literal length past the literals"
end
local need = op + ll + ml
if need > cap then
st.op = op
if not grow(st, need) then
return "LIMIT", "output over the size limit"
end
out = st.out
cap = blen(out)
end
if ll > 0 then
bcopy(out, op, litSrc, lp, ll)
op += ll
lp += ll
end
if offset > op - frameStart or offset < 1 then
return "CORRUPT", "match offset before the frame start"
end
local from = op - offset
if offset >= ml then
bcopy(out, op, out, from, ml)
op += ml
elseif offset == 1 then
bfill(out, op, readu8(out, from), ml)
op += ml
else
-- overlapping: copy in chunks of `offset` bytes (each chunk's source precedes its destination)
local left = ml
while left > 0 do
local n = if left < offset then left else offset
bcopy(out, op, out, from, n)
op += n
from += n
left -= n
end
end
end
if off ~= 0 then
return "CORRUPT", "sequences bitstream size mismatch"
end
local rest = litEnd - lp
if rest > 0 then
if op + rest > cap then
st.op = op
if not grow(st, op + rest) then
return "LIMIT", "output over the size limit"
end
out = st.out
end
bcopy(out, op, litSrc, lp, rest)
op += rest
end
st.op = op
st.rep1, st.rep2, st.rep3 = rep1, rep2, rep3
return nil, nil
end
-- decompress(b, start, stop, maxBytes, verify) -> out, length, consumedEnd | nil, code, message, offset
function Decode.decompress(b: buffer, start: number, stop: number, maxBytes: number, verify: boolean): (buffer?, any, any, any)
local st: any = {
out = bcreate(math.min(maxBytes, math.max(4096, (stop - start) * 3))),
op = 0,
maxBytes = maxBytes,
lit = bcreate(BLOCK_MAX + 64),
huf = bcreate(2048 * 2),
hufBits = nil,
norm = table.create(256, 0),
tabs = {},
rle = { bcreate(4), bcreate(4), bcreate(4) },
dyn = { bcreate(512 * 4), bcreate(256 * 4), bcreate(512 * 4) },
frameStart = 0,
rep1 = 1,
rep2 = 4,
rep3 = 8,
}
local pos = start
local frames = 0
if stop - start < 4 then
return nil, "TRUNCATED", "not a zstd stream (too short)", start
end
while pos < stop do
if pos + 4 > stop then
return nil, "TRUNCATED", "truncated frame magic", pos
end
local magic = readu32(b, pos)
if band(magic, 0xFFFFFFF0) == 0x184D2A50 then
if pos + 8 > stop then
return nil, "TRUNCATED", "truncated skippable frame", pos
end
local size = readu32(b, pos + 4)
if pos + 8 + size > stop then
return nil, "TRUNCATED", "truncated skippable frame", pos
end
pos += 8 + size
frames += 1
continue
end
if magic ~= MAGIC then
return nil, "CORRUPT", if frames == 0 then "bad magic" else "unknown data after frame " .. frames, pos
end
pos += 4
if pos + 1 > stop then
return nil, "TRUNCATED", "truncated frame header", pos
end
local fhd = readu8(b, pos)
pos += 1
local fcsFlag = rshift(fhd, 6)
local single = band(fhd, 0x20) ~= 0
if band(fhd, 8) ~= 0 then
return nil, "CORRUPT", "reserved frame header bit set", pos - 1
end
local checksum = band(fhd, 4) ~= 0
local didFlag = band(fhd, 3)
local didSize = if didFlag == 3 then 4 else didFlag
local fcsSize = if fcsFlag == 0 then (if single then 1 else 0) else lshift(1, fcsFlag)
local hsize = (if single then 0 else 1) + didSize + fcsSize
if pos + hsize > stop then
return nil, "TRUNCATED", "truncated frame header", pos
end
local windowSize = 0
if not single then
local wd = readu8(b, pos)
pos += 1
local wlog = 10 + rshift(wd, 3)
if wlog > 41 then
return nil, "CORRUPT", "bad window size", pos - 1
end
local base = 2 ^ wlog
windowSize = base + base / 8 * band(wd, 7)
end
local did = 0
if didSize == 1 then
did = readu8(b, pos)
elseif didSize == 2 then
did = readu16(b, pos)
elseif didSize == 4 then
did = readu32(b, pos)
end
pos += didSize
if did ~= 0 then
return nil, "UNSUPPORTED", "dictionaries are not supported (dictionary " .. did .. ")", pos - didSize
end
local fcs = -1
if fcsSize == 1 then
fcs = readu8(b, pos)
elseif fcsSize == 2 then
fcs = readu16(b, pos) + 256
elseif fcsSize == 4 then
fcs = readu32(b, pos)
elseif fcsSize == 8 then
fcs = readu32(b, pos) + readu32(b, pos + 4) * 4294967296
end
pos += fcsSize
if single then
windowSize = fcs
end
local blockMax = math.min(windowSize, BLOCK_MAX)
local frameStart = st.op
if fcs >= 0 then
if frameStart + fcs > st.maxBytes then
return nil, "LIMIT", string.format("frame content size %d is over the %d byte limit", fcs, st.maxBytes), pos
end
if frameStart + fcs > blen(st.out) then
grow(st, frameStart + fcs)
end
end
st.frameStart = frameStart
st.rep1, st.rep2, st.rep3 = 1, 4, 8
st.hufBits = nil
table.clear(st.tabs)
-- blocks
local last = false
repeat
if pos + 3 > stop then
return nil, "TRUNCATED", "truncated block header", pos
end
local bh = readu16(b, pos) + readu8(b, pos + 2) * 65536
last = band(bh, 1) ~= 0
local btype = band(rshift(bh, 1), 3)
local bsize = rshift(bh, 3)
pos += 3
if bsize > blockMax then
return nil, "CORRUPT", "block larger than the maximum block size", pos - 3
end
if btype == 0 then
if pos + bsize > stop then
return nil, "TRUNCATED", "truncated raw block", pos
end
if st.op + bsize > blen(st.out) and not grow(st, st.op + bsize) then
return nil, "LIMIT", "output over the size limit", pos
end
bcopy(st.out, st.op, b, pos, bsize)
st.op += bsize
pos += bsize
elseif btype == 1 then
if pos + 1 > stop then
return nil, "TRUNCATED", "truncated RLE block", pos
end
if st.op + bsize > blen(st.out) and not grow(st, st.op + bsize) then
return nil, "LIMIT", "output over the size limit", pos
end
bfill(st.out, st.op, readu8(b, pos), bsize)
st.op += bsize
pos += 1
elseif btype == 2 then
if pos + bsize > stop then
return nil, "TRUNCATED", "truncated compressed block", pos
end
if bsize == 0 then
return nil, "CORRUPT", "empty compressed block", pos
end
local code, msg = block(b, pos, pos + bsize, st)
if code then
return nil, code, msg, pos
end
pos += bsize
else
return nil, "CORRUPT", "reserved block type", pos - 3
end
until last
local size = st.op - frameStart
if fcs >= 0 and size ~= fcs then
return nil, "CORRUPT", string.format("frame decoded to %d bytes, header says %d", size, fcs), pos
end
if checksum then
if pos + 4 > stop then
return nil, "TRUNCATED", "missing content checksum", pos
end
if verify then
local _, lo = Xxh64.hash(st.out, frameStart, size)
local want = readu32(b, pos)
if lo ~= want then
return nil, "CHECKSUM", string.format("content checksum mismatch (%08x, expected %08x)", lo, want), pos
end
end
pos += 4
end
frames += 1
end
return st.out, st.op, pos
end
Decode.hash = Xxh64.hash
return Decode