--!strict -- archive/bz2: a .bz2 file as a single-stream archive: one entry, the decompressed data (codecs/Bzip2; concatenated -- streams are joined, as bzip2 -d does). The entry is named after the file without its .bz2 (".tbz2" -> ".tar"), -- else "data"; the api unwraps a .tar.bz2 into the tar inside (meta.stream). Read only. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Archive = require("@formats/containers/Archive") local Bzip2 = require("@formats/codecs/Bzip2") -- ------------------------------------------------------------------------------------------------ contract local Bz2 = { name = "bz2", category = "archive", extensions = { "bz2", "tbz2", "tbz" }, mime = { "application/x-bzip2" }, deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/Bzip2" }, caps = { decode = true, encode = false, stream = true }, } export type DecodeOptions = { maxBytes: number?, -- refuse larger output (default 2^30) name: string?, -- the file name (the api passes it): names the entry } -- ------------------------------------------------------------------------------------------------ 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