--!strict --!native --!optimize 2 -- codecs/Lzma/Decode: the LZMA range decoder and LZ state machine, shared by raw LZMA (.lzma, 7z) and LZMA2 (xz, 7z). -- Written from the LZMA specification and its reference decoder (LzmaSpec.cpp, Igor Pavlov, public domain); the -- structure (probability model layout, state transitions, distance / length decoding) follows that document. -- -- The output buffer is also the dictionary: everything decoded stays in memory, so a match may reach back to the last -- dictionary reset (st.dictStart). A decoder state (new) carries the probabilities, the LZ state, the four rep -- distances, a pending match remainder (st.remLen) and the range coder across calls, so LZMA2 can feed it chunk by -- chunk. run() decodes until st.op reaches outEnd, an end marker, or an error. -- -- Never throws: every input read is bounds-checked (a read past the end counts in `over` and fails the call as -- "truncated"), every output write is preceded by a capacity check, and errors return nil, message. local readu8, readu16, writeu8, writeu16 = buffer.readu8, buffer.readu16, buffer.writeu8, buffer.writeu16 local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len local rshift, band = bit32.rshift, bit32.band -- probability offsets (u16 entries) local IS_MATCH = 0 -- 12 states x 16 pos states local IS_REP = 192 local IS_REP_G0 = 204 local IS_REP_G1 = 216 local IS_REP_G2 = 228 local IS_REP0_LONG = 240 -- 12 x 16 local POS_SLOT = 432 -- 4 x 64 local SPEC_POS = 688 -- 115 local ALIGN = 803 -- 16 local LEN = 819 -- choice, choice2, low 16 x 8, mid 16 x 8, high 256 local REP_LEN = 1333 local LITERAL = 1847 -- 0x300 << (lc + lp) local TOP = 16777216 -- 2^24 local Decode = {} export type State = { out: buffer, cap: number, op: number, -- bytes decoded so far (the next write offset) dictStart: number, -- the last dictionary reset: matches may not reach before it maxBytes: number, probs: buffer, nprobs: number, lc: number, lp: number, pb: number, state: number, rep0: number, rep1: number, rep2: number, rep3: number, remLen: number, -- a match cut by outEnd, finished by the next run range: number, code: number, } -- new(cap, maxBytes) -> a decoder state with an empty output buffer of capacity cap function Decode.new(cap: number, maxBytes: number): State local c = math.max(64, math.min(cap, maxBytes)) return { out = bcreate(c), cap = c, op = 0, dictStart = 0, maxBytes = maxBytes, probs = bcreate(2), nprobs = 0, lc = 0, lp = 0, pb = 0, state = 0, rep0 = 0, rep1 = 0, rep2 = 0, rep3 = 0, remLen = 0, range = 0xFFFFFFFF, code = 0, } end -- setProps(st, lc, lp, pb) -> ok, message?: new literal / position parameters (resets the probabilities) function Decode.setProps(st: State, lc: number, lp: number, pb: number): (boolean, string?) if lc > 8 or lp > 4 or pb > 4 or lc < 0 or lp < 0 or pb < 0 then return false, "bad lc / lp / pb" end st.lc, st.lp, st.pb = lc, lp, pb local n = LITERAL + 0x300 * 2 ^ (lc + lp) if blen(st.probs) < n * 2 then st.probs = bcreate(n * 2) end st.nprobs = n Decode.resetState(st) return true, nil end -- resetState(st): probabilities to 1/2, LZ state and reps to 0 function Decode.resetState(st: State) local p = st.probs for i = 0, st.nprobs - 1 do writeu16(p, i * 2, 1024) end st.state = 0 st.rep0, st.rep1, st.rep2, st.rep3 = 0, 0, 0, 0 st.remLen = 0 end -- resetDict(st): matches may no longer reach before the current position function Decode.resetDict(st: State) st.dictStart = st.op st.remLen = 0 end -- rcInit(st, buf, ip, iend) -> next ip | nil, message: the 5 range coder init bytes function Decode.rcInit(st: State, b: buffer, ip: number, iend: number): (number?, string?) if ip + 5 > iend then return nil, "truncated range coder init" end if readu8(b, ip) ~= 0 then return nil, "bad range coder init byte" end st.code = readu8(b, ip + 1) * 16777216 + readu8(b, ip + 2) * 65536 + readu8(b, ip + 3) * 256 + readu8(b, ip + 4) st.range = 0xFFFFFFFF if st.code == st.range then return nil, "bad range coder init" end return ip + 5, nil end -- ensure(st, need) -> ok: grow the output to hold need bytes (bounded by maxBytes) local function ensure(st: State, need: number): boolean if need <= st.cap then return true end if need > st.maxBytes then return false end local c = math.min(math.max(st.cap * 2, need, 65536), st.maxBytes) local nb = bcreate(c) bcopy(nb, 0, st.out, 0, st.op) st.out = nb st.cap = c return true end Decode.ensure = ensure -- copy(st, n, b, ip): append n stored bytes (LZMA2 uncompressed chunks); the caller checked the input range function Decode.copy(st: State, n: number, b: buffer, ip: number): (boolean, string?) if not ensure(st, st.op + n) then return false, "limit: output over maxBytes" end bcopy(st.out, st.op, b, ip, n) st.op += n return true, nil end -- the range decoder state while run() executes (module upvalues: the helpers below are created once, so LuaJIT -- traces stay valid across calls; run() is not re-entrant, and never yields) local EMPTY = bcreate(2) local probs: buffer = EMPTY local inb: buffer = EMPTY local range, code, ip, iend, over = 0, 0, 0, 0, 0 -- decode one bit with the probability at index i local function bit(i: number): number local p = i * 2 local prob = readu16(probs, p) local bound = rshift(range, 11) * prob local r if code < bound then range = bound writeu16(probs, p, prob + rshift(2048 - prob, 5)) r = 0 else range -= bound code -= bound writeu16(probs, p, prob - rshift(prob, 5)) r = 1 end if range < TOP then range *= 256 if ip < iend then code = code * 256 + readu8(inb, ip) else code *= 256 over += 1 end ip += 1 end return r end local function tree(base: number, nbits: number): number local m = 1 for _ = 1, nbits do m = m * 2 + bit(base + m) end return m - 2 ^ nbits end local function reverse(base: number, nbits: number): number local m = 1 local sym = 0 for i = 0, nbits - 1 do local b = bit(base + m) m = m * 2 + b sym += b * 2 ^ i end return sym end local function direct(nbits: number): number local res = 0 for _ = 1, nbits do range = rshift(range, 1) local b = 0 if code >= range then code -= range b = 1 end res = res * 2 + b if range < TOP then range *= 256 if ip < iend then code = code * 256 + readu8(inb, ip) else code *= 256 over += 1 end ip += 1 end end return res end local function length(base: number, posState: number): number if bit(base) == 0 then return tree(base + 2 + posState * 8, 3) end if bit(base + 1) == 0 then return 8 + tree(base + 130 + posState * 8, 3) end return 16 + tree(base + 258, 8) end -- run(st, buf, ip, iend, outEnd) -> status, ip | nil, message. status: "full" (st.op reached outEnd) or "eos" (end -- marker). The range coder must have been initialised (rcInit). function Decode.run(st: State, inb0: buffer, ip0: number, iend0: number, outEnd: number): (string?, any) probs = st.probs inb = inb0 iend = iend0 local out = st.out local cap = st.cap local op = st.op local dictStart = st.dictStart range, code = st.range, st.code ip = ip0 over = 0 local state = st.state local rep0, rep1, rep2, rep3 = st.rep0, st.rep1, st.rep2, st.rep3 local lc = st.lc local lcShift = 2 ^ (8 - lc) local lpMask = 2 ^ st.lp - 1 local pbMask = 2 ^ st.pb - 1 local lcMul = 2 ^ lc local status: string? = nil local msg: string? = nil -- a pending match from the previous call local remLen = st.remLen if remLen > 0 then local n = math.min(remLen, outEnd - op) if n > 0 then if op + n > cap then st.op = op if not ensure(st, op + n) then probs, inb = EMPTY, EMPTY return nil, "limit: output over maxBytes" end out, cap = st.out, st.cap end local src = op - rep0 - 1 for k = 0, n - 1 do writeu8(out, op + k, readu8(out, src + k)) end op += n remLen -= n end end while true do if op >= outEnd then status = "full" break end if over > 0 then msg = "truncated" break end if op + 273 > cap then st.op = op if not ensure(st, math.min(op + 273, outEnd)) then msg = "limit: output over maxBytes" break end out, cap = st.out, st.cap end local pos = op - dictStart local posState = band(pos, pbMask) -- is match? (inlined bit) local pidx = (IS_MATCH + state * 16 + posState) * 2 local prob = readu16(probs, pidx) local bound = rshift(range, 11) * prob if code < bound then range = bound writeu16(probs, pidx, prob + rshift(2048 - prob, 5)) if range < TOP then range *= 256 if ip < iend then code = code * 256 + readu8(inb, ip) else code *= 256 over += 1 end ip += 1 end -- literal local prev = if op > dictStart then readu8(out, op - 1) else 0 local base = LITERAL + 0x300 * (band(pos, lpMask) * lcMul + prev // lcShift) local sym = 1 if state >= 7 then local mpos = op - rep0 - 1 local matchByte = if mpos >= dictStart then readu8(out, mpos) else 0 repeat local matchBit = band(rshift(matchByte, 7), 1) matchByte *= 2 local b = bit(base + (1 + matchBit) * 256 + sym) sym = sym * 2 + b if matchBit ~= b then break end until sym >= 256 end while sym < 256 do local p2 = (base + sym) * 2 local pr = readu16(probs, p2) local bd = rshift(range, 11) * pr if code < bd then range = bd writeu16(probs, p2, pr + rshift(2048 - pr, 5)) sym = sym * 2 else range -= bd code -= bd writeu16(probs, p2, pr - rshift(pr, 5)) sym = sym * 2 + 1 end if range < TOP then range *= 256 if ip < iend then code = code * 256 + readu8(inb, ip) else code *= 256 over += 1 end ip += 1 end end writeu8(out, op, sym - 256) op += 1 state = if state < 4 then 0 elseif state < 10 then state - 3 else state - 6 else range -= bound code -= bound writeu16(probs, pidx, prob - rshift(prob, 5)) if range < TOP then range *= 256 if ip < iend then code = code * 256 + readu8(inb, ip) else code *= 256 over += 1 end ip += 1 end local len if bit(IS_REP + state) == 0 then -- simple match len = length(LEN, posState) state = if state < 7 then 7 else 10 rep3, rep2, rep1 = rep2, rep1, rep0 local lenState = if len < 3 then len else 3 local slot = tree(POS_SLOT + lenState * 64, 6) if slot < 4 then rep0 = slot else local nd = slot // 2 - 1 local dist = (2 + slot % 2) * 2 ^ nd if slot < 14 then dist += reverse(SPEC_POS + dist - slot, nd) else dist += direct(nd - 4) * 16 dist += reverse(ALIGN, 4) end rep0 = dist end if rep0 == 0xFFFFFFFF then status = "eos" break end else if bit(IS_REP_G0 + state) == 0 then if bit(IS_REP0_LONG + state * 16 + posState) == 0 then -- short rep: one byte at rep0 if op == dictStart or rep0 >= op - dictStart then msg = "distance past the dictionary start" break end state = if state < 7 then 9 else 11 writeu8(out, op, readu8(out, op - rep0 - 1)) op += 1 continue end else local dist if bit(IS_REP_G1 + state) == 0 then dist = rep1 else if bit(IS_REP_G2 + state) == 0 then dist = rep2 else dist = rep3 rep3 = rep2 end rep2 = rep1 end rep1 = rep0 rep0 = dist end len = length(REP_LEN, posState) state = if state < 7 then 8 else 11 end -- copy len + 2 bytes from rep0 + 1 back if rep0 >= op - dictStart then msg = "distance past the dictionary start" break end local n = len + 2 local room = outEnd - op if n > room then remLen = n - room n = room end local src = op - rep0 - 1 if rep0 + 1 >= n then bcopy(out, op, out, src, n) else for k = 0, n - 1 do writeu8(out, op + k, readu8(out, src + k)) end end op += n end end st.op = op st.range, st.code = range, code st.state = state st.rep0, st.rep1, st.rep2, st.rep3 = rep0, rep1, rep2, rep3 st.remLen = remLen probs, inb = EMPTY, EMPTY -- do not keep the caller's buffers alive if msg then return nil, msg end if over > 0 then return nil, "truncated" end return status, ip end -- finish(st) -> a buffer of exactly the decoded bytes function Decode.finish(st: State): buffer if st.cap == st.op then return st.out end local b = bcreate(st.op) bcopy(b, 0, st.out, 0, st.op) return b end return Decode