Files
rosetta/src/Rosetta/archive/bz2/init.luau
T

63 lines
2.0 KiB
Luau

--!strict
-- archive/bz2: a .bz2 file as a single-stream archive of one entry (codecs/compress/Bzip2). Supports: read,
-- concatenated streams joined as bzip2 -d does. Not supported: writing, randomised blocks (bzip2 0.9.0 and older).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Archive = require("@rosetta/containers/Archive")
local Bzip2 = require("@rosetta/codecs/compress/Bzip2")
-- ------------------------------------------------------------------------------------------------ contract
local Bz2 = {
name = "bz2",
category = "archive",
extensions = { "bz2", "tbz2", "tbz" },
mime = { "application/x-bzip2" },
deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Bzip2" },
caps = { decode = true, encode = false, stream = true },
}
export type DecodeOptions = {
maxBytes: number?, -- default 2^30
name: string?,
}
-- ------------------------------------------------------------------------------------------------ sniff
function Bz2.sniff(r: Bytes.Reader): number
local h = r:peek(10)
if #h < 10 or string.sub(h, 1, 3) ~= "BZh" then
return 0
end
local lv = string.byte(h, 4)
if lv < 0x31 or lv > 0x39 then
return 0
end
local magic = string.sub(h, 5, 10)
if magic == "\x31\x41\x59\x26\x53\x59" or magic == "\x17\x72\x45\x38\x50\x90" then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Bz2.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local out, consumed = Bzip2.decompress(r.buf, r.base, r.limit - r.base, { maxBytes = opts and opts.maxBytes })
if not out then
return nil, consumed
end
local a = Archive.new("bz2")
a.meta.stream = true
Archive.put(a, {
name = Archive.streamName(opts, Bz2.extensions),
size = buffer.len(out),
compressedSize = consumed - r.base,
method = "bzip2",
dir = false,
data = out,
})
return a, nil
end
return Bz2