Files
rosetta/src/Formats/archive/br/init.luau
T

77 lines
2.9 KiB
Luau

--!strict
-- archive/br: a Brotli (RFC 7932) stream as a single-entry archive (meta.stream: the api unwraps a .tar.br to the tar
-- inside). Decoding through codecs/Brotli. The entry is named after opts.name without ".br" (else "data").
-- Supports: read (eager decompression). Not supported: write (no Brotli compressor). Brotli has no magic number:
-- sniff accepts only data that decodes cleanly (the whole stream for small files, a 64 KB prefix for big ones), at a
-- low confidence, so the extension decides between candidates.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Brotli = require("@formats/codecs/Brotli")
local Archive = require("@formats/containers/Archive")
-- ------------------------------------------------------------------------------------------------ contract
local Br = {
name = "br",
category = "archive",
extensions = { "br" },
mime = { "application/x-brotli" },
deps = { "core/Err", "core/Bytes", "codecs/Brotli", "containers/Archive" },
caps = { decode = true, encode = false, stream = true },
}
export type DecodeOptions = {
name: string?, -- the file name (the api passes it): the entry is named after it
maxBytes: number?, -- refuse output larger than this (default 2^30)
}
-- ------------------------------------------------------------------------------------------------ constants
local SNIFF_WHOLE = 262144 -- streams up to this size are decoded whole by sniff
local SNIFF_PREFIX = 65536
-- ------------------------------------------------------------------------------------------------ sniff
function Br.sniff(r: Bytes.Reader): number
local n = r:remaining()
if n == 0 then
return 0
end
if n <= SNIFF_WHOLE then
local out, consumed = Brotli.decompress(r.buf, r.pos, n, { maxBytes = 2 ^ 26 })
if out and consumed == r.limit then
return if buffer.len(out) > 0 then 0.3 else 0.05
end
return 0
end
local _, err = Brotli.decompress(r.buf, r.pos, SNIFF_PREFIX, { maxBytes = 2 ^ 22 })
if err and (err.code == Err.TRUNCATED or err.code == Err.LIMIT) then
return 0.05
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Br.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local n = r:remaining()
local out, consumed = Brotli.decompress(r.buf, r.pos, n, { maxBytes = opts and opts.maxBytes })
if not out then
local e: Err.Err = consumed
e.message = string.gsub(e.message, "^brotli: ", "")
return nil, e
end
local a = Archive.new("br")
a.meta.stream = true
a.meta.compressedSize = consumed - r.pos
Archive.put(a, {
name = Archive.streamName(opts, Br.extensions),
size = buffer.len(out),
compressedSize = consumed - r.pos,
method = "brotli",
dir = false,
data = out,
})
return a, nil
end
return Br