--!strict --!native --!optimize 2 -- codecs/Bzip2/Decode: bzip2 stream decoder (Julian Seward's format, as documented by the bzip2 1.0.x sources and -- Joe Tsai's "bzip2 format specification"). Written from the format description; no third-party code. -- Per block: MSB-first bit reader on a local 32-bit bit buffer, Huffman groups (10-bit lookup + canonical fallback for -- codes up to 20 bits), MTF + RUNA/RUNB, inverse BWT through one u32 vector (byte in the low 8 bits, next index -- above), RLE1 undo with the block CRC (CRC-32/BZIP2, MSB first) computed on the way out; the combined stream CRC is -- checked at the end-of-stream marker. Concatenated streams are decoded one after the other. -- Not supported: randomised blocks (written only by bzip2 0.9.0 and older). -- -- Never throws: every buffer access is in range by construction; failures return nil, message, kind -- ("truncated" | "corrupt" | "checksum" | "limit" | "unsupported"). local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len local Decode = {} -- CRC-32/BZIP2 table (polynomial 0x04C11DB7, not reflected) local CT = table.create(256, 0) for i = 0, 255 do local c = lshift(i, 24) for _ = 1, 8 do if band(c, 0x80000000) ~= 0 then c = bxor(lshift(c, 1), 0x04C11DB7) else c = lshift(c, 1) end end CT[i + 1] = c end Decode.crcTable = CT local MASK = table.create(33, 0) for i = 0, 32 do MASK[i + 1] = if i == 32 then 0xFFFFFFFF else 2 ^ i - 1 end local PBITS = 10 -- primary lookup width local PSIZE = 1024 local MAXGROUPS = 6 local MAXALPHA = 258 local MAXLEN = 20 -- scratch tables, reused across calls (single-threaded) local LOOK = bcreate(MAXGROUPS * PSIZE * 4) -- per group: sym * 32 + len (len <= PBITS), 0 = longer code / none local LENS = bcreate(MAXGROUPS * MAXALPHA) local PERM = table.create(MAXGROUPS * MAXALPHA, 0) -- per group: symbols in canonical order local FIRST = table.create(MAXGROUPS * (MAXLEN + 1), 0) -- first code of each length local COUNT = table.create(MAXGROUPS * (MAXLEN + 1), 0) local OFFS = table.create(MAXGROUPS * (MAXLEN + 1), 0) -- index into PERM of the first symbol of each length local MAXL = table.create(MAXGROUPS, 0) local CFTAB = table.create(257, 0) local MTF = table.create(256, 0) local SEQ = table.create(256, 0) -- build group g's tables from LENS[g*MAXALPHA .. + n): false when over-subscribed local function buildGroup(g: number, n: number): boolean local lbase = g * MAXALPHA local cbase = g * (MAXLEN + 1) for l = 0, MAXLEN do COUNT[cbase + l + 1] = 0 end local maxLen = 0 for s = 0, n - 1 do local l = readu8(LENS, lbase + s) COUNT[cbase + l + 1] += 1 if l > maxLen then maxLen = l end end MAXL[g + 1] = maxLen -- canonical codes: by length, then symbol local code, idx = 0, 0 for l = 1, MAXLEN do FIRST[cbase + l + 1] = code OFFS[cbase + l + 1] = idx local c = COUNT[cbase + l + 1] code += c idx += c if code > 2 ^ l then return false end code *= 2 end -- perm + lookup local pbase = g * MAXALPHA local tbase = g * PSIZE * 4 bfill(LOOK, tbase, 0, PSIZE * 4) local next = table.create(MAXLEN + 1, 0) for l = 1, MAXLEN do next[l + 1] = OFFS[cbase + l + 1] end for s = 0, n - 1 do local l = readu8(LENS, lbase + s) local k = next[l + 1] next[l + 1] = k + 1 PERM[pbase + k + 1] = s if l <= PBITS then local c = FIRST[cbase + l + 1] + (k - OFFS[cbase + l + 1]) local shift = PBITS - l local from = lshift(c, shift) local entry = s * 32 + l for j = from, from + lshift(1, shift) - 1 do writeu32(LOOK, tbase + j * 4, entry) end end end return true end local function grow(out: buffer, op: number, need: number): buffer local nb = bcreate(math.max(blen(out) * 2, need, 65536)) bcopy(nb, 0, out, 0, op) return nb end -- decode(b, o, e, maxBytes) -> out, n, consumedEnd | nil, message, kind function Decode.decode(b: buffer, o: number, e: number, maxBytes: number): (buffer?, any, any) local out = bcreate(math.min(math.max(65536, (e - o) * 4), maxBytes + 1)) local op = 0 local p = o -- next input byte (may run past e: zeros are fed, and the overrun is detected) local bb, bc = 0, 0 local tt: buffer? = nil local ttSize = 0 local streams = 0 local consumedEnd = o while true do -- stream header (byte aligned) if streams > 0 then if p + 4 > e or readu8(b, p) ~= 0x42 or readu8(b, p + 1) ~= 0x5A or readu8(b, p + 2) ~= 0x68 then break -- trailing data after a stream is ignored, as bzip2 -d does end end if p + 4 > e then return nil, "truncated stream header", "truncated" end if readu8(b, p) ~= 0x42 or readu8(b, p + 1) ~= 0x5A or readu8(b, p + 2) ~= 0x68 then return nil, "bad magic", "corrupt" end local level = readu8(b, p + 3) - 0x30 if level < 1 or level > 9 then return nil, "bad block size", "corrupt" end local maxBlock = level * 100000 if ttSize < maxBlock then tt = bcreate(maxBlock * 4) ttSize = maxBlock end local T = tt :: buffer p += 4 bb, bc = 0, 0 local combined = 0 while true do -- 48-bit magic + 32-bit CRC while bc <= 24 do bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end local m1 = band(rshift(bb, bc - 24), 0xFFFFFF) bc -= 24 while bc <= 24 do bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end local m2 = band(rshift(bb, bc - 24), 0xFFFFFF) bc -= 24 while bc <= 24 do bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end local c1 = band(rshift(bb, bc - 16), 0xFFFF) bc -= 16 while bc <= 24 do bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end local storedCrc = band(rshift(bb, bc - 16), 0xFFFF) + c1 * 65536 bc -= 16 if (p - o) * 8 - bc > (e - o) * 8 then return nil, "truncated block header", "truncated" end if m1 == 0x177245 and m2 == 0x385090 then if storedCrc ~= combined then return nil, string.format("stream CRC mismatch (%08x, expected %08x)", combined, storedCrc), "checksum" end -- align to the byte after the stream p -= bc // 8 bb, bc = 0, 0 break end if m1 ~= 0x314159 or m2 ~= 0x265359 then return nil, "bad block magic", "corrupt" end -- randomised bit, origPtr, symbol map while bc <= 24 do bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end local rnd = band(rshift(bb, bc - 1), 1) bc -= 1 while bc <= 24 do bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end local origPtr = band(rshift(bb, bc - 24), 0xFFFFFF) bc -= 24 if rnd ~= 0 then return nil, "randomised blocks (bzip2 0.9.0 and older) are not supported", "unsupported" end while bc <= 24 do bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end local used = band(rshift(bb, bc - 16), 0xFFFF) bc -= 16 local nInUse = 0 for i = 0, 15 do if band(used, lshift(1, 15 - i)) ~= 0 then while bc <= 24 do bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end local bits = band(rshift(bb, bc - 16), 0xFFFF) bc -= 16 for j = 0, 15 do if band(bits, lshift(1, 15 - j)) ~= 0 then SEQ[nInUse + 1] = i * 16 + j nInUse += 1 end end end end if nInUse == 0 then return nil, "no symbols in use", "corrupt" end local alphaSize = nInUse + 2 -- groups and selectors while bc <= 24 do bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end local nGroups = band(rshift(bb, bc - 3), 7) bc -= 3 local nSelectors = band(rshift(bb, bc - 15), 0x7FFF) bc -= 15 if nGroups < 2 or nGroups > 6 then return nil, "bad number of Huffman groups", "corrupt" end if nSelectors < 1 then return nil, "no selectors", "corrupt" end local selectors = buffer.create(nSelectors) local mtfg0, mtfg1, mtfg2, mtfg3, mtfg4, mtfg5 = 0, 1, 2, 3, 4, 5 for i = 0, nSelectors - 1 do local j = 0 while true do if bc <= 24 then bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end bc -= 1 if band(rshift(bb, bc), 1) == 0 then break end j += 1 if j >= nGroups then return nil, "bad selector", "corrupt" end end -- move-to-front over the group list local v if j == 0 then v = mtfg0 elseif j == 1 then v = mtfg1 mtfg1 = mtfg0 elseif j == 2 then v = mtfg2 mtfg2, mtfg1 = mtfg1, mtfg0 elseif j == 3 then v = mtfg3 mtfg3, mtfg2, mtfg1 = mtfg2, mtfg1, mtfg0 elseif j == 4 then v = mtfg4 mtfg4, mtfg3, mtfg2, mtfg1 = mtfg3, mtfg2, mtfg1, mtfg0 else v = mtfg5 mtfg5, mtfg4, mtfg3, mtfg2, mtfg1 = mtfg4, mtfg3, mtfg2, mtfg1, mtfg0 end mtfg0 = v writeu8(selectors, i, v) end if (p - o) * 8 - bc > (e - o) * 8 then return nil, "truncated selectors", "truncated" end -- code lengths (delta coded) for g = 0, nGroups - 1 do while bc <= 24 do bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end local len = band(rshift(bb, bc - 5), 31) bc -= 5 for s = 0, alphaSize - 1 do while true do if len < 1 or len > MAXLEN then return nil, "bad code length", "corrupt" end if bc <= 24 then bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end bc -= 1 if band(rshift(bb, bc), 1) == 0 then break end bc -= 1 if band(rshift(bb, bc), 1) == 0 then len += 1 else len -= 1 end end writeu8(LENS, g * MAXALPHA + s, len) end if not buildGroup(g, alphaSize) then return nil, "over-subscribed Huffman code", "corrupt" end end if (p - o) * 8 - bc > (e - o) * 8 then return nil, "truncated code lengths", "truncated" end -- MTF / RUNA / RUNB symbols -> T low bytes for i = 0, 255 do CFTAB[i + 1] = 0 MTF[i + 1] = i end local eob = alphaSize - 1 local nblock = 0 local selIdx = 0 local left = 0 local g = 0 local tbase, pbase, cbase, gmax = 0, 0, 0, 0 local runLen, runBit = 0, 1 while true do if left == 0 then if selIdx >= nSelectors then return nil, "ran out of selectors", "corrupt" end g = readu8(selectors, selIdx) selIdx += 1 left = 50 tbase = g * PSIZE * 4 pbase = g * MAXALPHA cbase = g * (MAXLEN + 1) gmax = MAXL[g + 1] end left -= 1 while bc <= 24 do bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) p += 1 bc += 8 end local ent = readu32(LOOK, tbase + band(rshift(bb, bc - PBITS), PSIZE - 1) * 4) local sym if ent ~= 0 then bc -= band(ent, 31) sym = rshift(ent, 5) else -- a code longer than PBITS: canonical search local v = band(rshift(bb, bc - gmax), MASK[gmax + 1]) sym = -1 for l = PBITS + 1, gmax do local c = rshift(v, gmax - l) local f = FIRST[cbase + l + 1] local k = c - f if k >= 0 and k < COUNT[cbase + l + 1] then sym = PERM[pbase + OFFS[cbase + l + 1] + k + 1] bc -= l break end end if sym < 0 then return nil, "bad Huffman code", "corrupt" end end if sym <= 1 then -- RUNA / RUNB: bijective base-2 run length of the front symbol runLen += runBit * (sym + 1) runBit *= 2 if runLen > maxBlock then return nil, "run past the block size", "corrupt" end else if runLen > 0 then if nblock + runLen > maxBlock then return nil, "block larger than its declared size", "corrupt" end local ch = SEQ[MTF[1] + 1] CFTAB[ch + 1] += runLen for k = nblock, nblock + runLen - 1 do writeu32(T, k * 4, ch) end nblock += runLen runLen, runBit = 0, 1 end if sym == eob then break end local idx = sym - 1 if idx >= nInUse then return nil, "bad MTF index", "corrupt" end if nblock >= maxBlock then return nil, "block larger than its declared size", "corrupt" end local v = MTF[idx + 1] for k = idx, 1, -1 do MTF[k + 1] = MTF[k] end MTF[1] = v local ch = SEQ[v + 1] CFTAB[ch + 1] += 1 writeu32(T, nblock * 4, ch) nblock += 1 end if (p - o) * 8 - bc > (e - o) * 8 then return nil, "truncated block data", "truncated" end end if origPtr >= nblock then return nil, "bad BWT origin pointer", "corrupt" end -- inverse BWT: T[pos] |= i << 8 at each byte's sorted position local sum = 0 for i = 0, 255 do local c = CFTAB[i + 1] CFTAB[i + 1] = sum sum += c end for i = 0, nblock - 1 do local ch = band(readu32(T, i * 4), 255) local k = CFTAB[ch + 1] CFTAB[ch + 1] = k + 1 writeu32(T, k * 4, bor(readu32(T, k * 4), lshift(i, 8))) end -- walk, undo RLE1, CRC if op + nblock + 4096 > blen(out) then out = grow(out, op, op + nblock + 4096) end local cap = blen(out) local crc = 0xFFFFFFFF local tPos = rshift(readu32(T, origPtr * 4), 8) local last, run = -1, 0 local i = 0 while i < nblock do local v = readu32(T, tPos * 4) local ch = band(v, 255) tPos = rshift(v, 8) i += 1 if run == 4 then -- ch is a repeat count for the previous byte if ch > 0 then if op + ch > maxBytes then return nil, "output larger than maxBytes", "limit" end if op + ch + 256 > cap then out = grow(out, op, op + ch + nblock - i + 4096) cap = blen(out) end bfill(out, op, last, ch) op += ch for _ = 1, ch do crc = bxor(lshift(crc, 8), CT[bxor(rshift(crc, 24), last) + 1]) end end run = 0 last = -1 else if ch == last then run += 1 else run = 1 last = ch end if op + 256 > cap then if op >= maxBytes then return nil, "output larger than maxBytes", "limit" end out = grow(out, op, op + nblock - i + 4096) cap = blen(out) end writeu8(out, op, ch) op += 1 crc = bxor(lshift(crc, 8), CT[bxor(rshift(crc, 24), ch) + 1]) end end if op > maxBytes then return nil, "output larger than maxBytes", "limit" end crc = bxor(crc, 0xFFFFFFFF) if crc ~= storedCrc then return nil, string.format("block CRC mismatch (%08x, expected %08x)", crc, storedCrc), "checksum" end combined = bxor(bor(lshift(combined, 1), rshift(combined, 31)), crc) end streams += 1 consumedEnd = p if p >= e then break end end return out, op, consumedEnd end return Decode