--!strict -- codecs/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec -- (layer 3): archive/bz2 and tar.bz2 build on it. Written from the format description (no third-party code). -- Supports: block sizes 1..9, every Huffman group layout, block and stream CRCs, concatenated streams (as bzip2 -d). -- Not supported: randomised blocks (bzip2 0.9.0 and older; Err.UNSUPPORTED), compression. -- -- local Bzip2 = require("@formats/codecs/Bzip2") -- local out, consumedEnd = Bzip2.decompress(buf) -- | nil, Err -- local out = Bzip2.decompress(buf, offset, length, { maxBytes = 2^24 }) -- -- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / LIMIT / ARG). local Err = require("@formats/core/Err") local Decode = require("@formats/codecs/Bzip2/Decode") local Bzip2 = {} export type Options = { maxBytes: number?, -- refuse output larger than this (default 2^30) } local KINDS = { truncated = Err.TRUNCATED, corrupt = Err.CORRUPT, checksum = Err.CHECKSUM, limit = Err.LIMIT, unsupported = Err.UNSUPPORTED, } -- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err function Bzip2.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) local b: buffer if type(buf) == "string" then b = buffer.fromstring(buf) elseif type(buf) == "buffer" then b = buf else return nil, Err.new(Err.ARG, "Bzip2.decompress: expected a buffer or a string, got " .. typeof(buf)) end local n = buffer.len(b) local o = offset or 0 if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then return nil, Err.new(Err.ARG, "Bzip2.decompress: bad offset " .. tostring(offset)) end local l = length or (n - o) if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then return nil, Err.new(Err.ARG, "Bzip2.decompress: bad length " .. tostring(length)) end l = math.min(l, n - o) local maxBytes = if opts and opts.maxBytes ~= nil then opts.maxBytes else 2 ^ 30 if type(maxBytes) ~= "number" or maxBytes < 0 then return nil, Err.new(Err.ARG, "Bzip2.decompress: bad maxBytes") end local out, nOut, consumed = Decode.decode(b, o, o + l, maxBytes) if not out then return nil, Err.new(KINDS[consumed] or Err.CORRUPT, "bzip2: " .. tostring(nOut), o) end local res = out if buffer.len(out) ~= nOut then res = buffer.create(nOut) buffer.copy(res, 0, out, 0, nOut) end return res, consumed end -- crc(buf, offset?, length?) -> the CRC-32/BZIP2 of a range (the block CRC bzip2 stores) function Bzip2.crc(buf: buffer, offset: number?, length: number?): number local CT = Decode.crcTable local o = offset or 0 local e = o + (length or (buffer.len(buf) - o)) local c = 0xFFFFFFFF for i = o, e - 1 do c = bit32.bxor(bit32.lshift(c, 8), CT[bit32.bxor(bit32.rshift(c, 24), buffer.readu8(buf, i)) + 1]) end return bit32.bxor(c, 0xFFFFFFFF) end return Bzip2