56 lines
1.8 KiB
Luau
56 lines
1.8 KiB
Luau
--!strict
|
|
-- codecs/compress/Zstd: Zstandard decompression (RFC 8878), written from the specification; no dictionaries.
|
|
local Err = require("@rosetta/core/Err")
|
|
local Bytes = require("@rosetta/core/Bytes")
|
|
local Decode = require("@rosetta/codecs/compress/Zstd/Decode")
|
|
|
|
local Zstd = {}
|
|
|
|
export type Options = {
|
|
maxBytes: number?,
|
|
verify: boolean?,
|
|
}
|
|
|
|
-- magic numbers: a zstd frame, and skippable frames (0x184D2A50 .. 0x184D2A5F)
|
|
Zstd.MAGIC = "\40\181\47\253"
|
|
|
|
function Zstd.isFrame(buf: buffer, offset: number?): boolean
|
|
local o = offset or 0
|
|
if type(buf) ~= "buffer" or o < 0 or o + 4 > buffer.len(buf) then
|
|
return false
|
|
end
|
|
local m = buffer.readu32(buf, o)
|
|
return m == 0xFD2FB528 or bit32.band(m, 0xFFFFFFF0) == 0x184D2A50
|
|
end
|
|
|
|
-- data after the last frame that is not a frame is an error, as zstd -d does
|
|
function Zstd.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any)
|
|
local b, o, l, aerr = Bytes.span("Zstd.decompress", buf, offset, length)
|
|
if not b then
|
|
return nil, aerr
|
|
end
|
|
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, "Zstd.decompress: bad maxBytes " .. tostring(maxBytes))
|
|
end
|
|
local verify = not (opts and opts.verify == false)
|
|
local out, len, consumed, at = Decode.decompress(b, o, o + l, maxBytes, verify)
|
|
if not out then
|
|
return nil, Err.from(consumed, at, len)
|
|
end
|
|
if buffer.len(out) ~= len then
|
|
local r = buffer.create(len)
|
|
buffer.copy(r, 0, out, 0, len)
|
|
out = r
|
|
end
|
|
return out, consumed
|
|
end
|
|
|
|
function Zstd.xxh64(buf: buffer, offset: number?, length: number?): (number, number)
|
|
local o = math.clamp(offset or 0, 0, buffer.len(buf))
|
|
local l = math.clamp(length or (buffer.len(buf) - o), 0, buffer.len(buf) - o)
|
|
return Decode.hash(buf, o, l)
|
|
end
|
|
|
|
return Zstd
|