codecs/compress: comments to specs only
This commit is contained in:
1 parent
f1ad32105b
commit
f626fb4295
23 files changed
+123
-498
No files matched your search
@@ -1,18 +1,9 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/compress/Brotli/Decode: a Brotli (RFC 7932) decoder over a whole in-memory stream. Written from the RFC, with the
|
||||
-- reference decoder (google/brotli c/dec/decode.c, MIT) as the authority on edge cases (simple prefix code alphabet
|
||||
-- widths, repeat codes, padding checks, the large-window extension). Supports every meta-block kind (compressed,
|
||||
-- uncompressed, metadata), block types / counts, the four literal context modes, context maps with RLE and inverse
|
||||
-- move-to-front, NPOSTFIX / NDIRECT distances, the static dictionary with all 121 transforms, window sizes 10..24 and
|
||||
-- large windows (10..30). The whole output is kept, so the window is only used to tell copies from dictionary words.
|
||||
--
|
||||
-- Bits are read LSB first into a bit buffer of up to 32 bits. Prefix codes decode through tables indexed by the next
|
||||
-- 8 bits; entries are symbol * 32 + length (length < 16), or a link offset * 32 + 16 + subtable bits.
|
||||
--
|
||||
-- Nothing here throws: every buffer access is checked or in range by construction (the output buffer is sized for each
|
||||
-- meta-block before it is decoded); bad data returns nil, message.
|
||||
-- codecs/compress/Brotli/Decode: a Brotli (RFC 7932) decoder, with the large-window extension (windows 10..30).
|
||||
-- Written from the RFC, with google/brotli c/dec/decode.c (MIT) as the authority on edge cases.
|
||||
-- Prefix table entry: symbol * 32 + length (length < 16), or a link offset * 32 + 16 + subtable bits (8-bit primary).
|
||||
local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift
|
||||
local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32
|
||||
local bcreate, bcopy, blen, bfill = buffer.create, buffer.copy, buffer.len, buffer.fill
|
||||
@@ -27,7 +18,6 @@ export type Static = {
|
||||
transforms: { number }, -- 121 x (prefix id, type, suffix id)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local CL_ORDER = { 1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15 }
|
||||
local CLP_LEN = { 2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2, 3, 2, 2, 2, 4 }
|
||||
local CLP_VAL = { 0, 4, 3, 2, 0, 4, 3, 1, 0, 4, 3, 2, 0, 4, 3, 5 }
|
||||
@@ -54,7 +44,6 @@ end
|
||||
local NTRANSFORMS = 121
|
||||
local MAX_ALLOWED_DISTANCE = 0x7FFFFFFC
|
||||
|
||||
-- 8-bit reversal
|
||||
local REV8 = bcreate(256)
|
||||
for i = 0, 255 do
|
||||
local r, v = 0, i
|
||||
@@ -65,19 +54,15 @@ for i = 0, 255 do
|
||||
writeu8(REV8, i, r)
|
||||
end
|
||||
local function reverse(code: number, len: number): number
|
||||
-- len <= 15
|
||||
local r = readu8(REV8, band(code, 255)) * 256 + readu8(REV8, band(rshift(code, 8), 255))
|
||||
return rshift(r, 16 - len)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ prefix tables
|
||||
local count = table.create(16, 0)
|
||||
local nextc = table.create(16, 0)
|
||||
local subBits = table.create(256, 0)
|
||||
local subOff = table.create(256, 0)
|
||||
|
||||
-- tableSize(lens, n) -> the entries build() will write (256 + subtables), or -1 for an over-subscribed set.
|
||||
-- Also leaves count / nextc / subBits ready for build().
|
||||
local function prepare(lens: buffer, n: number): number
|
||||
for l = 1, 16 do
|
||||
count[l] = 0
|
||||
@@ -135,7 +120,6 @@ local function prepare(lens: buffer, n: number): number
|
||||
return size
|
||||
end
|
||||
|
||||
-- build(lens, n, T, at): the table prepared by prepare() at entry offset `at` of T (T must have room)
|
||||
local function build(lens: buffer, n: number, T: buffer, at: number)
|
||||
local single = -1
|
||||
local used = 0
|
||||
@@ -188,8 +172,7 @@ local function build(lens: buffer, n: number, T: buffer, at: number)
|
||||
end
|
||||
end
|
||||
|
||||
-- the largest distance alphabet whose distances stay under MAX_ALLOWED_DISTANCE (large windows); after the reference
|
||||
-- decoder's BrotliCalculateDistanceCodeLimit
|
||||
-- largest distance alphabet under MAX_ALLOWED_DISTANCE, as the reference's BrotliCalculateDistanceCodeLimit
|
||||
local function distanceLimit(maxDistance: number, npostfix: number, ndirect: number): number
|
||||
if maxDistance <= ndirect then
|
||||
return maxDistance + 16
|
||||
@@ -213,8 +196,6 @@ local function distanceLimit(maxDistance: number, npostfix: number, ndirect: num
|
||||
return bor(lshift(group, npostfix), postfix) + ndirect + 16 + 1
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decoder
|
||||
-- decompress(src, off, len, maxBytes, S, largeWindow) -> out, n, consumedEnd | nil, message
|
||||
function Decode.decompress(src: buffer, off: number, len: number, maxBytes: number, S: Static, largeWindow: boolean): (buffer?, any, number?)
|
||||
local lim = off + len
|
||||
local ip = off
|
||||
@@ -251,7 +232,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
|
||||
return (ip - lim) * 8 > bc
|
||||
end
|
||||
|
||||
-- prefix tables of the current meta-block: T (u32 entries), tpos entries used
|
||||
local T = bcreate(4096 * 4)
|
||||
local tpos = 0
|
||||
local LENS = bcreate(1128)
|
||||
@@ -273,7 +253,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
|
||||
return rshift(e, 5)
|
||||
end
|
||||
|
||||
-- install(n) -> base: the table for LENS[0 .. n - 1] appended to T, or -1
|
||||
local function install(n: number): number
|
||||
local size = prepare(LENS, n)
|
||||
if size < 0 then
|
||||
@@ -291,7 +270,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
|
||||
return base
|
||||
end
|
||||
|
||||
-- readCode(alphabetMax, limit) -> table base | -1 (corrupt)
|
||||
local function readCode(alphabetMax: number, limit: number): number
|
||||
bfill(LENS, 0, 0, limit)
|
||||
local hskip = bits(2)
|
||||
@@ -447,7 +425,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
|
||||
return BL_OFF[code + 1] + bits(BL_BITS[code + 1])
|
||||
end
|
||||
|
||||
-- readContextMap(size) -> ntrees, map buffer | -1
|
||||
local function readContextMap(size: number): (number, buffer)
|
||||
local ntrees = varLen8() + 1
|
||||
local map = bcreate(size)
|
||||
@@ -475,7 +452,7 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
|
||||
if i + reps > size then
|
||||
return -1, map
|
||||
end
|
||||
i += reps -- zeros (map is zero-filled)
|
||||
i += reps
|
||||
end
|
||||
if overrun() then
|
||||
return -1, map
|
||||
@@ -499,7 +476,7 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
|
||||
return ntrees, map
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------ stream header
|
||||
-- RFC 7932 9.1: stream header
|
||||
fill()
|
||||
local wbits
|
||||
local large = false
|
||||
@@ -545,7 +522,7 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
|
||||
local d0, d1, d2, d3 = 4, 11, 15, 16
|
||||
|
||||
while true do
|
||||
-- ---------------------------------------------------------------- meta-block header
|
||||
-- RFC 7932 9.2: meta-block header
|
||||
if overrun() then
|
||||
return nil, "truncated stream"
|
||||
end
|
||||
@@ -626,7 +603,7 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
|
||||
continue
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------- compressed meta-block
|
||||
-- RFC 7932 9.3: compressed meta-block data
|
||||
tpos = 0
|
||||
-- block types / counts: 1 = literals, 2 = commands, 3 = distances
|
||||
local nbtL, nbtI, nbtD = 1, 1, 1
|
||||
@@ -673,7 +650,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
|
||||
if ntreesD < 0 then
|
||||
return nil, "bad distance context map"
|
||||
end
|
||||
-- the tree groups
|
||||
local litBase = table.create(ntreesL, 0)
|
||||
for i = 1, ntreesL do
|
||||
local b = readCode(256, 256)
|
||||
@@ -703,7 +679,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
|
||||
if overrun() then
|
||||
return nil, "truncated meta-block header"
|
||||
end
|
||||
-- context map slices resolved to table bases
|
||||
local litMap = table.create(64 * nbtL, 0)
|
||||
for i = 0, 64 * nbtL - 1 do
|
||||
litMap[i + 1] = litBase[readu8(cmapL, i) + 1]
|
||||
@@ -713,7 +688,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
|
||||
distMap[i + 1] = distBase[readu8(cmapD, i) + 1]
|
||||
end
|
||||
|
||||
-- block state: current type, previous type
|
||||
local typeL, prevL = 0, 1
|
||||
local typeI, prevI = 0, 1
|
||||
local typeD, prevD = 0, 1
|
||||
@@ -727,7 +701,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
|
||||
if ip > lim + 4 then
|
||||
return nil, "truncated stream"
|
||||
end
|
||||
-- command block switch
|
||||
if cntI == 0 then
|
||||
local t = decodeSym(btTreeI)
|
||||
if t == 1 then
|
||||
@@ -759,7 +732,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
|
||||
if ce > 0 then
|
||||
cpyLen += bits(ce)
|
||||
end
|
||||
-- literals
|
||||
if insLen > remaining then
|
||||
return nil, "insert past the meta-block end"
|
||||
end
|
||||
@@ -815,7 +787,6 @@ function Decode.decompress(src: buffer, off: number, len: number, maxBytes: numb
|
||||
break
|
||||
end
|
||||
end
|
||||
-- distance
|
||||
local dist
|
||||
local push = true
|
||||
if cell < 2 then
|
||||
|
||||
@@ -1,16 +1,7 @@
|
||||
--!strict
|
||||
-- codecs/compress/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written
|
||||
-- from the RFC (decoder in codecs/compress/Brotli/Decode); the static dictionary, context table and word transforms come from
|
||||
-- google/brotli (MIT, licenses/brotli-LICENSE.txt) through codecs/compress/Brotli/Static (tools/brotli_static.py).
|
||||
-- Supports every RFC 7932 stream (window sizes 10..24, metadata / uncompressed / compressed meta-blocks, the static
|
||||
-- dictionary with all 121 transforms) and the large-window extension (opts.largeWindow). Not supported: compression,
|
||||
-- shared / compound dictionaries (draft "shared brotli").
|
||||
--
|
||||
-- local Brotli = require("@rosetta/codecs/compress/Brotli")
|
||||
-- local out, consumedEnd = Brotli.decompress(buf) -- buffer | string
|
||||
-- local out, err = Brotli.decompress(buf, offset, length, { maxBytes = 2^24 })
|
||||
--
|
||||
-- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / LIMIT / UNSUPPORTED / ARG).
|
||||
-- codecs/compress/Brotli: Brotli (RFC 7932) decompression, with the large-window extension.
|
||||
-- The static dictionary, context table and word transforms come from google/brotli (MIT, licenses/brotli-LICENSE.txt)
|
||||
-- through codecs/compress/Brotli/Static (tools/brotli_static.py).
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Crc32 = require("@rosetta/core/Crc32")
|
||||
@@ -22,11 +13,10 @@ local StaticData = require("@rosetta/codecs/compress/Brotli/Static")
|
||||
local Brotli = {}
|
||||
|
||||
export type Options = {
|
||||
maxBytes: number?, -- refuse output larger than this (default 2^30)
|
||||
largeWindow: boolean?, -- accept the large-window extension (windows up to 2^30; default true)
|
||||
maxBytes: number?,
|
||||
largeWindow: boolean?,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ static data
|
||||
-- the tables are base64 text (trusted, generated by tools/brotli_static.py)
|
||||
local function unbase64(s: string): buffer
|
||||
return Base64.decode(s) or buffer.create(0)
|
||||
@@ -34,7 +24,6 @@ end
|
||||
|
||||
local static: Decode.Static? = nil
|
||||
|
||||
-- tables() -> the decoded static data (inflated once, on first use)
|
||||
local function tables(): (Decode.Static?, Err.Err?)
|
||||
if static then
|
||||
return static, nil
|
||||
@@ -57,16 +46,11 @@ local function tables(): (Decode.Static?, Err.Err?)
|
||||
return static, nil
|
||||
end
|
||||
|
||||
-- dictionary() -> the 122784-byte RFC 7932 static dictionary (for tests and encoders)
|
||||
function Brotli.dictionary(): buffer?
|
||||
local s = tables()
|
||||
return if s then s.dictionary else nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decompress
|
||||
|
||||
-- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err. consumedEnd: the input offset just past
|
||||
-- the stream (trailing bytes are ignored).
|
||||
function Brotli.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any)
|
||||
local b, o, l, aerr = Bytes.span("Brotli.decompress", buf, offset, length)
|
||||
if not b then
|
||||
|
||||
@@ -1,16 +1,9 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/compress/Bzip2/Decode: bzip2 stream decoder (Julian Seward's format, as documented by the bzip2 1.0.x sources and
|
||||
-- Joe Tsai's "bzip2 format specification"). Written from the format description; no third-party code.
|
||||
-- Per block: MSB-first bit reader on a local 32-bit bit buffer, Huffman groups (10-bit lookup + canonical fallback for
|
||||
-- codes up to 20 bits), MTF + RUNA/RUNB, inverse BWT through one u32 vector (byte in the low 8 bits, next index
|
||||
-- above), RLE1 undo with the block CRC (CRC-32/BZIP2, MSB first) computed on the way out; the combined stream CRC is
|
||||
-- checked at the end-of-stream marker. Concatenated streams are decoded one after the other.
|
||||
-- Not supported: randomised blocks (written only by bzip2 0.9.0 and older).
|
||||
--
|
||||
-- Never throws: every buffer access is in range by construction; failures return nil, message, kind
|
||||
-- ("truncated" | "corrupt" | "checksum" | "limit" | "unsupported").
|
||||
-- codecs/compress/Bzip2/Decode: bzip2 stream decoder (bzip2 1.0.x sources, Joe Tsai's "bzip2 format specification").
|
||||
-- Huffman groups, MTF + RUNA/RUNB, inverse BWT, RLE1; block CRC-32/BZIP2 (MSB first) and the combined stream CRC.
|
||||
-- Written from the format description; no third-party code.
|
||||
local Crc32 = require("@rosetta/core/Crc32")
|
||||
local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
|
||||
local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32
|
||||
@@ -27,25 +20,23 @@ for i = 0, 32 do
|
||||
MASK[i + 1] = if i == 32 then 0xFFFFFFFF else 2 ^ i - 1
|
||||
end
|
||||
|
||||
local PBITS = 10 -- primary lookup width
|
||||
local PBITS = 10
|
||||
local PSIZE = 1024
|
||||
local MAXGROUPS = 6
|
||||
local MAXALPHA = 258
|
||||
local MAXLEN = 20
|
||||
|
||||
-- scratch tables, reused across calls (single-threaded)
|
||||
local LOOK = bcreate(MAXGROUPS * PSIZE * 4) -- per group: sym * 32 + len (len <= PBITS), 0 = longer code / none
|
||||
local LOOK = bcreate(MAXGROUPS * PSIZE * 4)
|
||||
local LENS = bcreate(MAXGROUPS * MAXALPHA)
|
||||
local PERM = table.create(MAXGROUPS * MAXALPHA, 0) -- per group: symbols in canonical order
|
||||
local FIRST = table.create(MAXGROUPS * (MAXLEN + 1), 0) -- first code of each length
|
||||
local PERM = table.create(MAXGROUPS * MAXALPHA, 0)
|
||||
local FIRST = table.create(MAXGROUPS * (MAXLEN + 1), 0)
|
||||
local COUNT = table.create(MAXGROUPS * (MAXLEN + 1), 0)
|
||||
local OFFS = table.create(MAXGROUPS * (MAXLEN + 1), 0) -- index into PERM of the first symbol of each length
|
||||
local OFFS = table.create(MAXGROUPS * (MAXLEN + 1), 0)
|
||||
local MAXL = table.create(MAXGROUPS, 0)
|
||||
local CFTAB = table.create(257, 0)
|
||||
local MTF = table.create(256, 0)
|
||||
local SEQ = table.create(256, 0)
|
||||
|
||||
-- build group g's tables from LENS[g*MAXALPHA .. + n): false when over-subscribed
|
||||
local function buildGroup(g: number, n: number): boolean
|
||||
local lbase = g * MAXALPHA
|
||||
local cbase = g * (MAXLEN + 1)
|
||||
@@ -74,7 +65,6 @@ local function buildGroup(g: number, n: number): boolean
|
||||
end
|
||||
code *= 2
|
||||
end
|
||||
-- perm + lookup
|
||||
local pbase = g * MAXALPHA
|
||||
local tbase = g * PSIZE * 4
|
||||
bfill(LOOK, tbase, 0, PSIZE * 4)
|
||||
@@ -106,11 +96,10 @@ local function grow(out: buffer, op: number, need: number): buffer
|
||||
return nb
|
||||
end
|
||||
|
||||
-- decode(b, o, e, maxBytes) -> out, n, consumedEnd | nil, message, kind
|
||||
function Decode.decode(b: buffer, o: number, e: number, maxBytes: number): (buffer?, any, any)
|
||||
local out = bcreate(math.min(math.max(65536, (e - o) * 4), maxBytes + 1))
|
||||
local op = 0
|
||||
local p = o -- next input byte (may run past e: zeros are fed, and the overrun is detected)
|
||||
local p = o
|
||||
local bb, bc = 0, 0
|
||||
local tt: buffer? = nil
|
||||
local ttSize = 0
|
||||
@@ -377,7 +366,6 @@ function Decode.decode(b: buffer, o: number, e: number, maxBytes: number): (buff
|
||||
bc -= band(ent, 31)
|
||||
sym = rshift(ent, 5)
|
||||
else
|
||||
-- a code longer than PBITS: canonical search
|
||||
local v = band(rshift(bb, bc - gmax), MASK[gmax + 1])
|
||||
sym = -1
|
||||
for l = PBITS + 1, gmax do
|
||||
@@ -442,7 +430,6 @@ function Decode.decode(b: buffer, o: number, e: number, maxBytes: number): (buff
|
||||
return nil, "bad BWT origin pointer", "corrupt"
|
||||
end
|
||||
|
||||
-- inverse BWT: T[pos] |= i << 8 at each byte's sorted position
|
||||
local sum = 0
|
||||
for i = 0, 255 do
|
||||
local c = CFTAB[i + 1]
|
||||
@@ -456,7 +443,6 @@ function Decode.decode(b: buffer, o: number, e: number, maxBytes: number): (buff
|
||||
writeu32(T, k * 4, bor(readu32(T, k * 4), lshift(i, 8)))
|
||||
end
|
||||
|
||||
-- walk, undo RLE1, CRC
|
||||
if op + nblock + 4096 > blen(out) then
|
||||
out = grow(out, op, op + nblock + 4096)
|
||||
end
|
||||
|
||||
@@ -1,14 +1,6 @@
|
||||
--!strict
|
||||
-- codecs/compress/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("@rosetta/codecs/compress/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).
|
||||
-- codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x).
|
||||
-- Written from the format description (no third-party code); randomised blocks (bzip2 0.9.0 and older) are unsupported.
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Decode = require("@rosetta/codecs/compress/Bzip2/Decode")
|
||||
@@ -16,10 +8,9 @@ local Decode = require("@rosetta/codecs/compress/Bzip2/Decode")
|
||||
local Bzip2 = {}
|
||||
|
||||
export type Options = {
|
||||
maxBytes: number?, -- refuse output larger than this (default 2^30)
|
||||
maxBytes: number?,
|
||||
}
|
||||
|
||||
-- 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, o, l, aerr = Bytes.span("Bzip2.decompress", buf, offset, length)
|
||||
if not b then
|
||||
@@ -41,7 +32,6 @@ function Bzip2.decompress(buf: buffer | string, offset: number?, length: number?
|
||||
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
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/compress/Deflate/Compress: a DEFLATE (RFC 1951) compressor. LZ77 over a 32 KB window with hash chains (chain depth
|
||||
-- and lazy matching by level), then per block the cheapest of stored / fixed-Huffman / dynamic-Huffman (codecs/entropy/Huffman
|
||||
-- length-limited codes). Level 0 = stored blocks only.
|
||||
--
|
||||
-- raw(buf, off, len, level) -> buffer. Never throws (the caller validated the arguments).
|
||||
-- codecs/compress/Deflate/Compress: a DEFLATE (RFC 1951) compressor: hash-chain LZ77 over a 32 KB window, then per
|
||||
-- block the cheapest of stored / fixed / dynamic Huffman, as zlib's levels.
|
||||
local Huffman = require("@rosetta/codecs/entropy/Huffman")
|
||||
|
||||
local readu8, writeu8, writeu16 = buffer.readu8, buffer.writeu8, buffer.writeu16
|
||||
@@ -15,11 +12,10 @@ local floor = math.floor
|
||||
local WSIZE = 32768
|
||||
local HSIZE = 65536
|
||||
local MAXMATCH = 258
|
||||
local BLOCKSYMS = 16384 -- symbols per block
|
||||
local BLOCKSYMS = 16384
|
||||
|
||||
-- per level (zlib's configuration_table): GOOD = a match this long quarters the chain for the lazy search, LAZY = no
|
||||
-- lazy search after a match this long, NICE = stop searching at this length, CHAIN = max chain steps. Levels 1-3 are
|
||||
-- greedy (no lazy matching).
|
||||
-- zlib's configuration_table: GOOD quarters the chain for the lazy search, LAZY = no lazy search after a match this
|
||||
-- long, NICE = stop searching at this length, CHAIN = max chain steps; levels 1-3 are greedy.
|
||||
local GOOD = { 4, 4, 4, 4, 8, 8, 8, 32, 32 }
|
||||
local LAZY = { 0, 0, 0, 4, 16, 16, 32, 128, 258 }
|
||||
local NICE = { 8, 16, 32, 16, 32, 128, 128, 258, 258 }
|
||||
@@ -66,14 +62,12 @@ end
|
||||
|
||||
local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }
|
||||
|
||||
-- fixed codes
|
||||
local FIXLEN = table.create(288, 0)
|
||||
for i = 1, 288 do
|
||||
FIXLEN[i] = if i <= 144 then 8 elseif i <= 256 then 9 elseif i <= 280 then 7 else 8
|
||||
end
|
||||
local FIXDLEN = table.create(30, 5)
|
||||
|
||||
-- reversed (LSB-first) canonical codes for lengths
|
||||
local function revCodes(lens: { number }): { number }
|
||||
local codes = Huffman.codes(lens)
|
||||
for i, l in lens do
|
||||
@@ -91,7 +85,6 @@ for i = 0, 32 do
|
||||
POW[i + 1] = 2 ^ i
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ bit output
|
||||
type Out = { buf: buffer, op: number, acc: number, cnt: number }
|
||||
|
||||
local function ensure(o: Out, n: number)
|
||||
@@ -102,7 +95,6 @@ local function ensure(o: Out, n: number)
|
||||
end
|
||||
end
|
||||
|
||||
-- put(v, n): n <= 24 bits, LSB first
|
||||
local function put(o: Out, v: number, n: number)
|
||||
local acc = o.acc + v * POW[o.cnt + 1]
|
||||
local cnt = o.cnt + n
|
||||
@@ -127,8 +119,6 @@ local function alignOut(o: Out)
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ blocks
|
||||
-- syms: L[i] = literal 0..255 or 256 + match length; D[i] = distance (0 for literals)
|
||||
local function storedBlock(o: Out, src: buffer, s: number, e: number, final: boolean)
|
||||
local p = s
|
||||
repeat
|
||||
@@ -209,7 +199,7 @@ local function block(o: Out, src: buffer, s: number, e: number, L: { number }, D
|
||||
for i = 1, hdist do
|
||||
all[hlit + i] = dlen[i]
|
||||
end
|
||||
local cs, cx = {}, {} -- symbol, extra value
|
||||
local cs, cx = {}, {}
|
||||
local cf = table.create(19, 0)
|
||||
local i = 1
|
||||
local total = hlit + hdist
|
||||
@@ -252,7 +242,6 @@ local function block(o: Out, src: buffer, s: number, e: number, L: { number }, D
|
||||
while hclen > 4 and clen[CLORDER[hclen] + 1] == 0 do
|
||||
hclen -= 1
|
||||
end
|
||||
-- costs in bits
|
||||
local dyn = 17 + 3 * hclen + extra
|
||||
for k = 1, 19 do
|
||||
dyn += cf[k] * clen[k]
|
||||
@@ -299,7 +288,6 @@ local function block(o: Out, src: buffer, s: number, e: number, L: { number }, D
|
||||
emitSymbols(o, L, D, nsym, revCodes(llen), llen, revCodes(dlen), dlen)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ LZ77
|
||||
local Compress = {}
|
||||
|
||||
function Compress.raw(src: buffer, off: number, len: number, level: number): buffer
|
||||
@@ -336,7 +324,6 @@ function Compress.raw(src: buffer, off: number, len: number, level: number): buf
|
||||
prev[p % WSIZE + 1] = head[h]
|
||||
head[h] = p
|
||||
end
|
||||
-- longest match at p among earlier positions: len (0 if < 3), dist
|
||||
local function find(p: number, steps: number): (number, number)
|
||||
local maxLen = math.min(MAXMATCH, e - p)
|
||||
if maxLen < 3 then
|
||||
@@ -360,7 +347,7 @@ function Compress.raw(src: buffer, off: number, len: number, level: number): buf
|
||||
end
|
||||
local nc = prev[c % WSIZE + 1]
|
||||
if nc >= c then
|
||||
break -- the slot was reused by a newer position: the chain ends here
|
||||
break
|
||||
end
|
||||
c = nc
|
||||
steps -= 1
|
||||
@@ -377,7 +364,7 @@ function Compress.raw(src: buffer, off: number, len: number, level: number): buf
|
||||
end
|
||||
|
||||
local p = off
|
||||
local stop3 = e - 3 -- positions with 3 bytes ahead can be hashed
|
||||
local stop3 = e - 3
|
||||
while p < e do
|
||||
local mlen, mdist = 0, 0
|
||||
if p <= stop3 then
|
||||
@@ -386,7 +373,6 @@ function Compress.raw(src: buffer, off: number, len: number, level: number): buf
|
||||
if mlen >= 3 and mlen < lazyMax and p + 1 <= stop3 then
|
||||
local l2, d2 = find(p + 1, if mlen >= good then maxChain // 4 else maxChain)
|
||||
if l2 > mlen then
|
||||
-- a literal now, the longer match from p + 1
|
||||
nsym += 1
|
||||
L[nsym] = readu8(src, p)
|
||||
D[nsym] = 0
|
||||
|
||||
@@ -2,15 +2,7 @@
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/compress/Deflate/Inflate: raw DEFLATE (RFC 1951) decoder: stored, fixed-Huffman and dynamic-Huffman blocks.
|
||||
-- Absorbed from deflate-luau src/Deflate/Inflate.luau (same author); the table builder moved to codecs/entropy/Huffman, whose
|
||||
-- entries are symbol * 32 + length (5 length bits instead of 4).
|
||||
--
|
||||
-- Bits are read LSB first into a 32-bit bit buffer (refilled 4 bytes at a time with one readu32 while the input
|
||||
-- lasts). Huffman codes decode through a codecs/entropy/Huffman LSB table indexed by the next LITBITS / DISTBITS bits; a longer
|
||||
-- code's primary slot links to a subtable, so a symbol is one or two table reads.
|
||||
--
|
||||
-- Nothing in this module throws on any input: every buffer read and write is bounds-checked, and corrupt data
|
||||
-- returns nil, message. (Native code must never throw: it crashes Roblox Studio.)
|
||||
-- Absorbed from deflate-luau src/Deflate/Inflate.luau (same author).
|
||||
local Huffman = require("@rosetta/codecs/entropy/Huffman")
|
||||
|
||||
local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
|
||||
@@ -20,7 +12,7 @@ local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buf
|
||||
local LITBITS, DISTBITS, CLBITS = 10, 8, 7
|
||||
local LITMASK, DISTMASK, CLMASK = 1023, 255, 127
|
||||
|
||||
-- length codes 257..285 and distance codes 0..29: base value, extra bits
|
||||
-- RFC 1951 3.2.5: length codes 257..285 and distance codes 0..29: base value, extra bits
|
||||
local LBASE = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 }
|
||||
local LEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }
|
||||
local DBASE = {
|
||||
@@ -28,15 +20,13 @@ local DBASE = {
|
||||
6145, 8193, 12289, 16385, 24577,
|
||||
}
|
||||
local DEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }
|
||||
-- the order code-length code lengths are sent in
|
||||
-- RFC 1951 3.2.7: the order the code-length code lengths are sent in
|
||||
local CLORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }
|
||||
|
||||
-- table capacities (entries): primary + one subtable per code longer than the primary width, worst case
|
||||
local LITCAP = Huffman.capacity(288, LITBITS, 15)
|
||||
local DISTCAP = Huffman.capacity(32, DISTBITS, 15)
|
||||
local CLCAP = Huffman.capacity(19, CLBITS, 7)
|
||||
|
||||
-- fixed Huffman tables
|
||||
local FLIT, FDIST = bcreate(LITCAP * 4), bcreate(DISTCAP * 4)
|
||||
local FLITS: number, FDISTS: number
|
||||
do
|
||||
@@ -53,7 +43,6 @@ end
|
||||
|
||||
local Inflate = {}
|
||||
|
||||
-- Grow out (capacity cap) to hold at least need bytes. Returns the new buffer and capacity.
|
||||
local function grow(out: buffer, op: number, need: number): (buffer, number)
|
||||
local cap = math.max(blen(out) * 2, need, 1024)
|
||||
local nb = bcreate(cap)
|
||||
@@ -61,12 +50,6 @@ local function grow(out: buffer, op: number, need: number): (buffer, number)
|
||||
return nb, cap
|
||||
end
|
||||
|
||||
-- Inflate src[start, endpos) into a buffer. cap: initial output capacity; exact: true = the output must fit in
|
||||
-- cap bytes (an error otherwise), false = grow as needed. prefix (with exact): stop at cap instead of failing and
|
||||
-- return what was inflated so far (at most cap bytes; Deflate.peek, for sniffing).
|
||||
-- dict: a preset dictionary (the data before the stream, e.g. MSZIP's previous block): out starts with a copy of it,
|
||||
-- distances may reach into it, and outLen includes it (cap does not).
|
||||
-- Returns out, outLen, consumedEnd (the input offset just past the final block) or nil, message.
|
||||
function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean, prefix: boolean?, dict: buffer?): (buffer?, any, number?)
|
||||
local op = 0
|
||||
if dict then
|
||||
@@ -267,7 +250,6 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex
|
||||
end
|
||||
local lsmask = lshift(1, lsub) - 1
|
||||
local dsmask = lshift(1, dsub) - 1
|
||||
-- the symbol loop
|
||||
while true do
|
||||
if bitcnt < 15 then
|
||||
if pos + 4 <= endpos then
|
||||
@@ -324,7 +306,6 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex
|
||||
if sym > 29 then
|
||||
return nil, "invalid literal/length code"
|
||||
end
|
||||
-- up to 5 length extra bits + a 15-bit distance code
|
||||
if bitcnt < 20 then
|
||||
if pos + 4 <= endpos then
|
||||
bitbuf = bor(bitbuf, lshift(readu32(src, pos), bitcnt))
|
||||
@@ -414,8 +395,7 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex
|
||||
local s = op - dist
|
||||
if dist >= len then
|
||||
if len <= 16 and op + 16 <= cap then
|
||||
-- straight-line 16-byte copy (the bytes past len are rewritten later): no inner loop, which
|
||||
-- keeps LuaJIT's traces simple; chunks read only bytes before op or already copied ones
|
||||
-- straight-line 16-byte copy for simple LuaJIT traces; it reads only bytes before op or already copied ones
|
||||
writeu32(out, op, readu32(out, s))
|
||||
writeu32(out, op + 4, readu32(out, s + 4))
|
||||
writeu32(out, op + 8, readu32(out, s + 8))
|
||||
@@ -432,7 +412,6 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex
|
||||
bfill(out, op, readu8(out, s), len)
|
||||
op += len
|
||||
else
|
||||
-- overlapping: the pattern of period dist, copied in growing non-overlapping chunks
|
||||
local rem = len
|
||||
while rem > 0 do
|
||||
local k = math.min(op - s, rem)
|
||||
|
||||
@@ -1,19 +1,6 @@
|
||||
--!strict
|
||||
-- codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
|
||||
-- A codec (layer 1), not a format: png, zip, gzip, woff, tiff, ... build on it. Absorbed from deflate-luau 1.0.0
|
||||
-- (same author; no third-party code); the compressor is new.
|
||||
--
|
||||
-- local Deflate = require("@rosetta/codecs/compress/Deflate")
|
||||
-- local out, err = Deflate.inflate(buf) -- raw deflate -> buffer, consumedEnd | nil, Err
|
||||
-- local out, err = Deflate.inflate(buf, off, len, size) -- a range, with the exact output size if known
|
||||
-- local out, err = Deflate.inflate(buf, off, len, size, dict) -- with a preset dictionary
|
||||
-- local out, err = Deflate.mszip(buf, { { offset, length, size }, ... }) -- MSZIP blocks ("CK" + deflate, chained)
|
||||
-- local out, err = Deflate.zlib(buf) -- checks the Adler-32
|
||||
-- local out, err = Deflate.gunzip(buf) -- checks CRC-32 + ISIZE, concatenates members
|
||||
-- local z = Deflate.compress(buf, { level = 6 }) -- raw deflate; also zlibCompress / gzip
|
||||
-- local head = Deflate.peek(buf, nil, nil, 512) -- the first 512 inflated bytes of gzip / zlib / raw
|
||||
--
|
||||
-- Never throws: bad data and bad arguments return nil, Err (core/Err codes TRUNCATED / CORRUPT / CHECKSUM / ARG).
|
||||
-- codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with zlib (RFC 1950) and gzip (RFC 1952).
|
||||
-- Absorbed from deflate-luau 1.0.0 (same author; no third-party code); the compressor is new.
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Crc32 = require("@rosetta/core/Crc32")
|
||||
@@ -42,11 +29,6 @@ local function inflateErr(msg: string, at: number?): Err.Err
|
||||
return Err.new(code, "inflate: " .. msg, at)
|
||||
end
|
||||
|
||||
-- inflate(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err. Raw deflate.
|
||||
-- expectedSize: the exact uncompressed size when known (a zip entry): the output is allocated once, and a stream
|
||||
-- that inflates to a different size is an error. consumedEnd is the input offset just past the final block.
|
||||
-- dict: a preset dictionary (up to 32 KB of data before the stream, as MSZIP's previous block): back references may
|
||||
-- reach into it; the result holds only the new bytes.
|
||||
function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, expectedSize: number?, dict: buffer?): (buffer?, any)
|
||||
local b, o, l, aerr = args("Deflate.inflate", buf, offset, length)
|
||||
if not b then
|
||||
@@ -82,7 +64,6 @@ function Deflate.inflate(buf: buffer | string, offset: number?, length: number?,
|
||||
return shrink(out, n), consumed
|
||||
end
|
||||
|
||||
-- zlib(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err
|
||||
function Deflate.zlib(buf: buffer | string, offset: number?, length: number?, expectedSize: number?): (buffer?, any)
|
||||
local b, o, l, aerr = args("Deflate.zlib", buf, offset, length)
|
||||
if not b then
|
||||
@@ -116,7 +97,6 @@ function Deflate.zlib(buf: buffer | string, offset: number?, length: number?, ex
|
||||
return out, consumed + 4
|
||||
end
|
||||
|
||||
-- gzipBody(b, p, e) -> the offset of a gzip member's deflate data (past FEXTRA / FNAME / FCOMMENT / FHCRC) | nil, Err
|
||||
local function gzipBody(b: buffer, p: number, e: number): (number?, Err.Err?)
|
||||
local flg = buffer.readu8(b, p + 3)
|
||||
if flg >= 0x20 then
|
||||
@@ -146,8 +126,6 @@ local function gzipBody(b: buffer, p: number, e: number): (number?, Err.Err?)
|
||||
return q, nil
|
||||
end
|
||||
|
||||
-- gunzip(buf, offset?, length?) -> buffer | nil, Err. Members are concatenated; trailing data after a member that is
|
||||
-- not another gzip member (zero padding, garbage) is ignored, as gzip -d does.
|
||||
function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?)
|
||||
local b, o, l, aerr = args("Deflate.gunzip", buf, offset, length)
|
||||
if not b then
|
||||
@@ -194,7 +172,6 @@ function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?):
|
||||
table.insert(parts, out)
|
||||
total += buffer.len(out)
|
||||
p = consumed + 8
|
||||
-- skip zero padding
|
||||
local z = p
|
||||
while z < e and buffer.readu8(b, z) == 0 do
|
||||
z += 1
|
||||
@@ -215,9 +192,6 @@ function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?):
|
||||
return res, nil
|
||||
end
|
||||
|
||||
-- peek(buf, offset?, length?, n) -> buffer | nil, Err: the first n bytes (fewer when the stream is shorter, or up to
|
||||
-- 258 fewer at a match boundary) a gzip member, zlib stream or raw deflate stream inflates to, without inflating
|
||||
-- the rest or checking checksums: for sniffing compressed files cheaply.
|
||||
function Deflate.peek(buf: buffer | string, offset: number?, length: number?, n: number): (buffer?, Err.Err?)
|
||||
local b, o, l, aerr = args("Deflate.peek", buf, offset, length)
|
||||
if not b then
|
||||
@@ -248,7 +222,7 @@ function Deflate.peek(buf: buffer | string, offset: number?, length: number?, n:
|
||||
end
|
||||
|
||||
export type CompressOptions = {
|
||||
level: number?, -- 0 (stored) .. 9 (best); default 6
|
||||
level: number?,
|
||||
}
|
||||
|
||||
local function level(opts: CompressOptions?): number?
|
||||
@@ -259,7 +233,6 @@ local function level(opts: CompressOptions?): number?
|
||||
return lv
|
||||
end
|
||||
|
||||
-- compress(buf, opts?) -> raw deflate buffer | nil, Err
|
||||
function Deflate.compress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?)
|
||||
local b = toBuffer(buf)
|
||||
local lv = level(opts)
|
||||
@@ -269,7 +242,6 @@ function Deflate.compress(buf: buffer | string, opts: CompressOptions?): (buffer
|
||||
return Compress.raw(b, 0, buffer.len(b), lv), nil
|
||||
end
|
||||
|
||||
-- zlibCompress(buf, opts?) -> zlib stream | nil, Err
|
||||
function Deflate.zlibCompress(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?)
|
||||
local b = toBuffer(buf)
|
||||
local lv = level(opts)
|
||||
@@ -290,7 +262,6 @@ function Deflate.zlibCompress(buf: buffer | string, opts: CompressOptions?): (bu
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- gzip(buf, opts?) -> gzip member (no name, mtime 0) | nil, Err
|
||||
function Deflate.gzip(buf: buffer | string, opts: CompressOptions?): (buffer?, Err.Err?)
|
||||
local b = toBuffer(buf)
|
||||
local lv = level(opts)
|
||||
@@ -309,10 +280,8 @@ function Deflate.gzip(buf: buffer | string, opts: CompressOptions?): (buffer?, E
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- mszip(buf, blocks) -> buffer | nil, Err: MSZIP data (Microsoft's blocked deflate, as in CAB folders and DirectX .x
|
||||
-- files): blocks = { { offset, length, size } }, each buf[offset, offset + length) = "CK" + a raw deflate stream that
|
||||
-- inflates to exactly size bytes using the previous block's output (up to 32 KB) as its dictionary. Returns the
|
||||
-- blocks' output concatenated.
|
||||
-- MSZIP (CAB folders, DirectX .x): each block is "CK" + a raw deflate stream using the previous block's output (up to
|
||||
-- 32 KB) as its dictionary.
|
||||
function Deflate.mszip(buf: buffer, blocks: { { offset: number, length: number, size: number } }): (buffer?, Err.Err?)
|
||||
local total = 0
|
||||
for _, b in blocks do
|
||||
@@ -343,7 +312,6 @@ function Deflate.mszip(buf: buffer, blocks: { { offset: number, length: number,
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- crc32 / adler32 (kept from deflate-luau's API; the same as core/Crc32.of / core/Adler32.of)
|
||||
Deflate.crc32 = function(buf: buffer | string, offset: number?, length: number?, crc: number?): number
|
||||
local b = toBuffer(buf) or buffer.create(0)
|
||||
return Crc32.of(b, offset, length, crc)
|
||||
|
||||
@@ -1,17 +1,9 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987: MPQ
|
||||
-- archive sectors, old installers, some game data files). A codec (layer 3). Written after the format as documented
|
||||
-- by Mark Adler's blast.c (zlib licence, licenses/blast-LICENSE.txt): the same constant code tables (run-length
|
||||
-- coded Huffman code lengths, length bases / extra bits), the bit order (LSB first, Huffman codes inverted); the
|
||||
-- decoder itself is new code.
|
||||
-- Supports: literal coding off (raw bytes) and on (Huffman coded), 1 / 2 / 4 KB dictionaries, the end code; stops
|
||||
-- early at maxOut bytes (MPQ sectors whose stream has no end code).
|
||||
--
|
||||
-- local out, err = Explode.decompress(buf, offset?, length?, maxOut?) -- buffer | nil, Err
|
||||
--
|
||||
-- Never throws: bad data returns nil, Err (TRUNCATED / CORRUPT / ARG / LIMIT).
|
||||
-- codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987).
|
||||
-- Code tables and bit order (LSB first, Huffman codes inverted) after Mark Adler's blast.c (zlib licence:
|
||||
-- licenses/blast-LICENSE.txt); the decoder is new code.
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
|
||||
@@ -33,7 +25,6 @@ local EXTRA = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8 }
|
||||
|
||||
type Code = { count: { number }, symbol: { number } }
|
||||
|
||||
-- canonical code from run-length coded lengths
|
||||
local function construct(rep: { number }): Code
|
||||
local lengths: { number } = {}
|
||||
for _, b in rep do
|
||||
@@ -64,7 +55,6 @@ local LIT = construct(LITLEN)
|
||||
local LEN = construct(LENLEN)
|
||||
local DIST = construct(DISTLEN)
|
||||
|
||||
-- decompress(buf, offset?, length?, maxOut?) -> buffer | nil, Err
|
||||
function Explode.decompress(buf: buffer | string, offset: number?, length: number?, maxOut: number?): (buffer?, Err.Err?)
|
||||
local b, o, l, aerr = Bytes.span("Explode.decompress", buf, offset, length)
|
||||
if not b then
|
||||
|
||||
@@ -1,26 +1,14 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md): decode and a greedy hash-chain-free encoder
|
||||
-- (the reference "fast" strategy: one 4-byte hash table, 64 KB window). A codec (layer 3): model/rbxm chunk bodies,
|
||||
-- and the LZ4 frame format (archive) builds on it. New code, written from the specification. Never throws.
|
||||
--
|
||||
-- local out, err = Lz4.decompress(src, offset?, length?, outSize?, opts?) -- a block -> buffer | nil, Err
|
||||
-- local packed = Lz4.compress(src, offset?, length?) -- -> buffer (a block) | nil, Err
|
||||
-- local dEnd, msg = Lz4.decodeInto(src, p, limit, dst, d, dstLimit, histStart?) -- low level (linked blocks)
|
||||
-- local n = Lz4.encodeInto(src, p, n, dst, d) -- low level; dst has bound(n) room
|
||||
-- Lz4.bound(n) -- worst-case block size for n bytes
|
||||
--
|
||||
-- decodeInto decodes one block from src[p, limit) to dst[d, dstLimit): matches may reach back to histStart (default
|
||||
-- d), so a frame decoder with linked blocks keeps the previous output in front of d. It returns the output end, or
|
||||
-- nil and a message ("truncated", "corrupt: ...", "limit: output ...") for the caller's Err.from.
|
||||
-- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md), decode and the reference "fast" encoder.
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
|
||||
local Lz4 = {}
|
||||
|
||||
export type Options = {
|
||||
maxBytes: number?, -- refuse output larger than this when outSize is not given (default 2^28)
|
||||
maxBytes: number?,
|
||||
}
|
||||
|
||||
local readu8, writeu8, readu16, writeu16, readu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32
|
||||
@@ -34,7 +22,6 @@ local MAX_OFFSET = 65535
|
||||
local HASH_BITS = 13
|
||||
local HASH_SIZE = 2 ^ HASH_BITS
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Lz4.decodeInto(src: buffer, p: number, limit: number, dst: buffer, d: number, dstLimit: number, histStart: number?): (number?, string?)
|
||||
local lo = histStart or d
|
||||
if limit > blen(src) or dstLimit > blen(dst) or p < 0 or d < 0 or lo < 0 or lo > d then
|
||||
@@ -107,7 +94,6 @@ function Lz4.decodeInto(src: buffer, p: number, limit: number, dst: buffer, d: n
|
||||
buffer.fill(dst, d, readu8(dst, s), ml)
|
||||
d += ml
|
||||
else
|
||||
-- an overlapping match repeats the off-byte pattern: copy what is already there, doubling each time
|
||||
local n = ml
|
||||
while n > 0 do
|
||||
local c = d - s
|
||||
@@ -122,8 +108,6 @@ function Lz4.decodeInto(src: buffer, p: number, limit: number, dst: buffer, d: n
|
||||
end
|
||||
end
|
||||
|
||||
-- decompress(src, offset?, length?, outSize?, opts?) -> buffer | nil, Err: one block. With outSize the output must be
|
||||
-- exactly that long (CORRUPT otherwise); without it the output grows up to opts.maxBytes.
|
||||
function Lz4.decompress(src: buffer | string, offset: number?, length: number?, outSize: number?, opts: Options?): (buffer?, Err.Err?)
|
||||
local b, o, l, aerr = Bytes.span("Lz4.decompress", src, offset, length)
|
||||
if not b then
|
||||
@@ -163,13 +147,10 @@ function Lz4.decompress(src: buffer | string, offset: number?, length: number?,
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- bound(n) -> the largest block n input bytes can produce
|
||||
function Lz4.bound(n: number): number
|
||||
return n + n // 255 + 16
|
||||
end
|
||||
|
||||
-- writes a length's 255-run extension at o; returns the next offset
|
||||
local function extend(dst: buffer, o: number, n: number): number
|
||||
while n >= 255 do
|
||||
writeu8(dst, o, 255)
|
||||
@@ -180,7 +161,7 @@ local function extend(dst: buffer, o: number, n: number): number
|
||||
return o + 1
|
||||
end
|
||||
|
||||
-- hash(v) -> 1 .. HASH_SIZE: Knuth's multiplicative hash (v * 2654435761 mod 2^32, top bits), exact in doubles
|
||||
-- Knuth's multiplicative hash (v * 2654435761 mod 2^32, top bits), exact in doubles
|
||||
local function hash(v: number): number
|
||||
local vl, vh = band(v, 0xFFFF), rshift(v, 16)
|
||||
local mid = (vh * 0x79B1 + vl * 0x9E37) % 65536
|
||||
@@ -189,7 +170,6 @@ end
|
||||
|
||||
local hashTable: { number } = table.create(HASH_SIZE, -1e9)
|
||||
|
||||
-- encodeInto(src, p, n, dst, d) -> the block's length: src[p, p + n) compressed to dst[d ..] (room for bound(n))
|
||||
function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: number): number
|
||||
local op = d
|
||||
local anchor = p
|
||||
@@ -209,7 +189,6 @@ function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: numbe
|
||||
local ref = ht[h]
|
||||
ht[h] = ip
|
||||
if ref >= p and ip - ref <= MAX_OFFSET and readu32(src, ref) == v then
|
||||
-- back over equal bytes before the match (into the pending literals)
|
||||
while ip > anchor and ref > p and readu8(src, ip - 1) == readu8(src, ref - 1) do
|
||||
ip -= 1
|
||||
ref -= 1
|
||||
@@ -247,7 +226,6 @@ function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: numbe
|
||||
ip = a
|
||||
anchor = ip
|
||||
skip = 64
|
||||
-- index the position just before the next one (better ratio at no cost)
|
||||
if ip - 2 >= p and ip - 2 < mflimit then
|
||||
local w = readu32(src, ip - 2)
|
||||
ht[hash(w)] = ip - 2
|
||||
@@ -258,7 +236,6 @@ function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: numbe
|
||||
end
|
||||
end
|
||||
end
|
||||
-- the last literals
|
||||
local lit = iend - anchor
|
||||
local tok = op
|
||||
op += 1
|
||||
@@ -275,7 +252,6 @@ function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: numbe
|
||||
return op - d
|
||||
end
|
||||
|
||||
-- compress(src, offset?, length?) -> buffer (one block) | nil, Err
|
||||
function Lz4.compress(src: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?)
|
||||
local b, o, l, aerr = Bytes.span("Lz4.compress", src, offset, length)
|
||||
if not b then
|
||||
|
||||
@@ -1,23 +1,9 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/compress/Lzh: the LHA family of LZSS decoders, used by archive/lha, archive/arj and archive/zoo:
|
||||
-- lh4 / lh5 / lh6 / lh7 / lhx static Huffman blocks (code-length "temp" table, 510 literal / length codes, offset
|
||||
-- bit-length codes); also ARJ methods 1..3 (= "lh6") and Zoo method 2 (= "lh5")
|
||||
-- lh1 adaptive Huffman (LHarc 1.x: 314 codes, grouped frequency tree) with fixed-length
|
||||
-- offset prefixes, 4 KB window
|
||||
-- lzs / lz5 LArc's plain LZSS (2 KB / 4 KB windows, flag bits / flag bytes)
|
||||
-- arj4 ARJ method 4 (unary-prefixed lengths and offsets, no Huffman)
|
||||
-- Every method decodes into a buffer of the known output size; the windows start filled as the original tools fill
|
||||
-- them (spaces; lz5's pattern), and offsets before the start of the output read that fill.
|
||||
-- Ported from lhasa 0.6.0 (Simon Howard, ISC licence: licenses/lhasa-LICENSE.txt): lh_new_decoder.c, lh1_decoder.c,
|
||||
-- lzs_decoder.c, lz5_decoder.c; the static Huffman tables are canonical codes built with codecs/entropy/Huffman instead
|
||||
-- of lhasa's trees. ARJ method 4 is written from the ARJ technical notes (unarj's decode_f description).
|
||||
--
|
||||
-- local out, err = Lzh.decode(src, off, len, outSize, "lh5") -- buffer | nil, message
|
||||
--
|
||||
-- Never throws: bad codes / truncated input return nil, message (truncated input: "truncated ..." after the bytes
|
||||
-- decoded so far would be useless, so nothing partial is returned). Not supported: pm0 / pm1 / pm2 (PMarc), lk7.
|
||||
-- codecs/compress/Lzh: the LHA family of LZSS decoders (lh1, lh4-lh7, lhx, lzs, lz5, ARJ 1-4, Zoo 2).
|
||||
-- Ported from lhasa 0.6.0 (Simon Howard, ISC: licenses/lhasa-LICENSE.txt); ARJ method 4 from the ARJ technical notes.
|
||||
-- Windows start filled as the original tools fill them (spaces; lz5's pattern); offsets before the output read it.
|
||||
local Huffman = require("@rosetta/codecs/entropy/Huffman")
|
||||
|
||||
local Lzh = {}
|
||||
@@ -26,9 +12,6 @@ local readu8, writeu8, readu32 = buffer.readu8, buffer.writeu8, buffer.readu32
|
||||
local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift
|
||||
local floor = math.floor
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ bit reader
|
||||
-- an MSB-first bit reader over src[pos, limit): acc holds cnt bits (cnt <= 32); past the end, zero bits are read and
|
||||
-- over counts them
|
||||
type Reader = { src: buffer, pos: number, limit: number, acc: number, cnt: number, over: number }
|
||||
|
||||
local function reader(src: buffer, off: number, len: number): Reader
|
||||
@@ -73,7 +56,6 @@ local function bits(r: Reader, n: number): number
|
||||
return v
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ static Huffman
|
||||
type Table = { tab: buffer, P: number, S: number, single: number }
|
||||
|
||||
local function newTable(nsym: number, P: number): Table
|
||||
@@ -145,7 +127,7 @@ local function readLengths(r: Reader, t: Table, nbits: number, maxN: number, spe
|
||||
writeu8(lens, i, l)
|
||||
if i == special then
|
||||
local z = bits(r, 2)
|
||||
i += z -- zeros (already zero)
|
||||
i += z
|
||||
end
|
||||
i += 1
|
||||
end
|
||||
@@ -235,7 +217,6 @@ local function decodeNew(src: buffer, off: number, len: number, out: buffer, n:
|
||||
return nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ lh1
|
||||
local NUM_CODES = 314
|
||||
local NUM_NODES = NUM_CODES * 2 - 1
|
||||
local REORDER = 32 * 1024
|
||||
@@ -261,7 +242,6 @@ end
|
||||
|
||||
local function decodeLh1(src: buffer, off: number, len: number, out: buffer, n: number): string?
|
||||
local r = reader(src, off, len)
|
||||
-- node arrays (0-based indexes stored at [i + 1])
|
||||
local leaf = table.create(NUM_NODES, false)
|
||||
local child = table.create(NUM_NODES, 0)
|
||||
local parent = table.create(NUM_NODES, 0)
|
||||
@@ -401,7 +381,7 @@ local function decodeLh1(src: buffer, off: number, len: number, out: buffer, n:
|
||||
end
|
||||
end
|
||||
local code = child[ni + 1]
|
||||
-- increment_for_code
|
||||
-- lhasa's increment_for_code
|
||||
if freq[1] >= REORDER then
|
||||
reconstruct()
|
||||
end
|
||||
@@ -438,8 +418,7 @@ local function decodeLh1(src: buffer, off: number, len: number, out: buffer, n:
|
||||
return nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ LArc lzs / lz5
|
||||
-- the ring of a 2 KB / 4 KB window (positions are absolute ring positions, not distances)
|
||||
-- LArc lzs / lz5: a 2 KB / 4 KB ring (absolute ring positions, not distances)
|
||||
local function decodeLzs(src: buffer, off: number, len: number, out: buffer, n: number): string?
|
||||
local r = reader(src, off, len)
|
||||
local ring = buffer.create(2048)
|
||||
@@ -549,7 +528,6 @@ local function decodeLz5(src: buffer, off: number, len: number, out: buffer, n:
|
||||
return nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ ARJ method 4
|
||||
local function decodeArj4(src: buffer, off: number, len: number, out: buffer, n: number): string?
|
||||
local r = reader(src, off, len)
|
||||
local function prefixed(start: number, stop: number): number
|
||||
@@ -591,10 +569,8 @@ local function decodeArj4(src: buffer, off: number, len: number, out: buffer, n:
|
||||
return nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ api
|
||||
Lzh.METHODS = { "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "arj4" }
|
||||
|
||||
-- decode(src, off, len, outSize, method) -> buffer | nil, message
|
||||
function Lzh.decode(src: buffer, off: number, len: number, outSize: number, method: string): (buffer?, string?)
|
||||
if off < 0 or len < 0 or off > buffer.len(src) or outSize < 0 or outSize ~= outSize then
|
||||
return nil, "bad arguments"
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/compress/Lzma/Crc64: CRC-64/XZ (ECMA-182 polynomial, reflected: 0xC96C5795D7870F42), the xz check type 4. The 64-bit
|
||||
-- value is kept as two u32 halves (hi, lo). Written from the xz file format specification. Never throws.
|
||||
-- codecs/compress/Lzma/Crc64: CRC-64/XZ (ECMA-182 polynomial, reflected: 0xC96C5795D7870F42), xz check type 4.
|
||||
-- Written from the xz file format specification; the 64-bit value is kept as two u32 halves (hi, lo).
|
||||
local band, bxor, rshift, lshift, bor = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift, bit32.bor
|
||||
local readu8 = buffer.readu8
|
||||
|
||||
@@ -23,7 +23,6 @@ end
|
||||
|
||||
local Crc64 = {}
|
||||
|
||||
-- of(buf, offset, length) -> hi, lo
|
||||
function Crc64.of(b: buffer, o: number, n: number): (number, number)
|
||||
local hi, lo = 0xFFFFFFFF, 0xFFFFFFFF
|
||||
for i = o, o + n - 1 do
|
||||
|
||||
@@ -1,17 +1,9 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/compress/Lzma/Decode: the LZMA range decoder and LZ state machine, shared by raw LZMA (.lzma, 7z) and LZMA2 (xz, 7z).
|
||||
-- Written from the LZMA specification and its reference decoder (LzmaSpec.cpp, Igor Pavlov, public domain); the
|
||||
-- structure (probability model layout, state transitions, distance / length decoding) follows that document.
|
||||
--
|
||||
-- The output buffer is also the dictionary: everything decoded stays in memory, so a match may reach back to the last
|
||||
-- dictionary reset (st.dictStart). A decoder state (new) carries the probabilities, the LZ state, the four rep
|
||||
-- distances, a pending match remainder (st.remLen) and the range coder across calls, so LZMA2 can feed it chunk by
|
||||
-- chunk. run() decodes until st.op reaches outEnd, an end marker, or an error.
|
||||
--
|
||||
-- Never throws: every input read is bounds-checked (a read past the end counts in `over` and fails the call as
|
||||
-- "truncated"), every output write is preceded by a capacity check, and errors return nil, message.
|
||||
-- codecs/compress/Lzma/Decode: the LZMA range decoder and LZ state machine, shared by LZMA (.lzma, 7z) and LZMA2.
|
||||
-- Follows the LZMA specification's reference decoder (LzmaSpec.cpp, Igor Pavlov, public domain): probability layout,
|
||||
-- state transitions, distance / length decoding.
|
||||
local readu8, readu16, writeu8, writeu16 = buffer.readu8, buffer.readu16, buffer.writeu8, buffer.writeu16
|
||||
local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
|
||||
local rshift, band = bit32.rshift, bit32.band
|
||||
@@ -37,8 +29,8 @@ local Decode = {}
|
||||
export type State = {
|
||||
out: buffer,
|
||||
cap: number,
|
||||
op: number, -- bytes decoded so far (the next write offset)
|
||||
dictStart: number, -- the last dictionary reset: matches may not reach before it
|
||||
op: number,
|
||||
dictStart: number,
|
||||
maxBytes: number,
|
||||
probs: buffer,
|
||||
nprobs: number,
|
||||
@@ -50,12 +42,11 @@ export type State = {
|
||||
rep1: number,
|
||||
rep2: number,
|
||||
rep3: number,
|
||||
remLen: number, -- a match cut by outEnd, finished by the next run
|
||||
remLen: number,
|
||||
range: number,
|
||||
code: number,
|
||||
}
|
||||
|
||||
-- new(cap, maxBytes) -> a decoder state with an empty output buffer of capacity cap
|
||||
function Decode.new(cap: number, maxBytes: number): State
|
||||
local c = math.max(64, math.min(cap, maxBytes))
|
||||
return {
|
||||
@@ -80,7 +71,6 @@ function Decode.new(cap: number, maxBytes: number): State
|
||||
}
|
||||
end
|
||||
|
||||
-- setProps(st, lc, lp, pb) -> ok, message?: new literal / position parameters (resets the probabilities)
|
||||
function Decode.setProps(st: State, lc: number, lp: number, pb: number): (boolean, string?)
|
||||
if lc > 8 or lp > 4 or pb > 4 or lc < 0 or lp < 0 or pb < 0 then
|
||||
return false, "bad lc / lp / pb"
|
||||
@@ -95,7 +85,6 @@ function Decode.setProps(st: State, lc: number, lp: number, pb: number): (boolea
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- resetState(st): probabilities to 1/2, LZ state and reps to 0
|
||||
function Decode.resetState(st: State)
|
||||
local p = st.probs
|
||||
for i = 0, st.nprobs - 1 do
|
||||
@@ -106,13 +95,11 @@ function Decode.resetState(st: State)
|
||||
st.remLen = 0
|
||||
end
|
||||
|
||||
-- resetDict(st): matches may no longer reach before the current position
|
||||
function Decode.resetDict(st: State)
|
||||
st.dictStart = st.op
|
||||
st.remLen = 0
|
||||
end
|
||||
|
||||
-- rcInit(st, buf, ip, iend) -> next ip | nil, message: the 5 range coder init bytes
|
||||
function Decode.rcInit(st: State, b: buffer, ip: number, iend: number): (number?, string?)
|
||||
if ip + 5 > iend then
|
||||
return nil, "truncated range coder init"
|
||||
@@ -128,7 +115,6 @@ function Decode.rcInit(st: State, b: buffer, ip: number, iend: number): (number?
|
||||
return ip + 5, nil
|
||||
end
|
||||
|
||||
-- ensure(st, need) -> ok: grow the output to hold need bytes (bounded by maxBytes)
|
||||
local function ensure(st: State, need: number): boolean
|
||||
if need <= st.cap then
|
||||
return true
|
||||
@@ -145,7 +131,6 @@ local function ensure(st: State, need: number): boolean
|
||||
end
|
||||
Decode.ensure = ensure
|
||||
|
||||
-- copy(st, n, b, ip): append n stored bytes (LZMA2 uncompressed chunks); the caller checked the input range
|
||||
function Decode.copy(st: State, n: number, b: buffer, ip: number): (boolean, string?)
|
||||
if not ensure(st, st.op + n) then
|
||||
return false, "limit: output over maxBytes"
|
||||
@@ -155,14 +140,12 @@ function Decode.copy(st: State, n: number, b: buffer, ip: number): (boolean, str
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- the range decoder state while run() executes (module upvalues: the helpers below are created once, so LuaJIT
|
||||
-- traces stay valid across calls; run() is not re-entrant, and never yields)
|
||||
-- module upvalues, so LuaJIT traces stay valid across calls (run() is not re-entrant)
|
||||
local EMPTY = bcreate(2)
|
||||
local probs: buffer = EMPTY
|
||||
local inb: buffer = EMPTY
|
||||
local range, code, ip, iend, over = 0, 0, 0, 0, 0
|
||||
|
||||
-- decode one bit with the probability at index i
|
||||
local function bit(i: number): number
|
||||
local p = i * 2
|
||||
local prob = readu16(probs, p)
|
||||
@@ -244,8 +227,6 @@ local function length(base: number, posState: number): number
|
||||
return 16 + tree(base + 258, 8)
|
||||
end
|
||||
|
||||
-- run(st, buf, ip, iend, outEnd) -> status, ip | nil, message. status: "full" (st.op reached outEnd) or "eos" (end
|
||||
-- marker). The range coder must have been initialised (rcInit).
|
||||
function Decode.run(st: State, inb0: buffer, ip0: number, iend0: number, outEnd: number): (string?, any)
|
||||
probs = st.probs
|
||||
inb = inb0
|
||||
@@ -268,7 +249,6 @@ function Decode.run(st: State, inb0: buffer, ip0: number, iend0: number, outEnd:
|
||||
local status: string? = nil
|
||||
local msg: string? = nil
|
||||
|
||||
-- a pending match from the previous call
|
||||
local remLen = st.remLen
|
||||
if remLen > 0 then
|
||||
local n = math.min(remLen, outEnd - op)
|
||||
@@ -469,7 +449,7 @@ function Decode.run(st: State, inb0: buffer, ip0: number, iend0: number, outEnd:
|
||||
st.state = state
|
||||
st.rep0, st.rep1, st.rep2, st.rep3 = rep0, rep1, rep2, rep3
|
||||
st.remLen = remLen
|
||||
probs, inb = EMPTY, EMPTY -- do not keep the caller's buffers alive
|
||||
probs, inb = EMPTY, EMPTY
|
||||
if msg then
|
||||
return nil, msg
|
||||
end
|
||||
@@ -479,7 +459,6 @@ function Decode.run(st: State, inb0: buffer, ip0: number, iend0: number, outEnd:
|
||||
return status, ip
|
||||
end
|
||||
|
||||
-- finish(st) -> a buffer of exactly the decoded bytes
|
||||
function Decode.finish(st: State): buffer
|
||||
if st.cap == st.op then
|
||||
return st.out
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/compress/Lzma/Filters: the branch-call-jump (BCJ) and delta decoding filters of xz and 7z, run in place over a whole
|
||||
-- decoded buffer range. Written from the xz file format specification and xz-embedded's xz_dec_bcj.c (Lasse Collin,
|
||||
-- public domain): x86, ARM, ARM-Thumb, PowerPC, SPARC, ARM64 and delta. Not supported: IA-64, RISC-V.
|
||||
-- Never throws: every access is inside [o, o + n).
|
||||
-- codecs/compress/Lzma/Filters: the xz / 7z branch-call-jump (BCJ) and delta decoding filters, in place.
|
||||
-- From the xz file format specification and xz-embedded's xz_dec_bcj.c (Lasse Collin, public domain).
|
||||
local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
|
||||
local band, bor, bxor, rshift, lshift, byteswap = bit32.band, bit32.bor, bit32.bxor, bit32.rshift, bit32.lshift, bit32.byteswap
|
||||
|
||||
@@ -19,7 +17,6 @@ local function msbyte(b: number): boolean
|
||||
return b == 0 or b == 0xFF
|
||||
end
|
||||
|
||||
-- x86(b, o, n, start): BCJ x86 decode; start = the stream position of b[o] (the filter's start offset)
|
||||
function Filters.x86(b: buffer, o: number, n: number, start: number)
|
||||
if n <= 4 then
|
||||
return
|
||||
@@ -167,7 +164,7 @@ function Filters.arm64(b: buffer, o: number, n: number, start: number)
|
||||
end
|
||||
end
|
||||
|
||||
-- delta(b, o, n, dist): b[i] += b[i - dist] (1 <= dist <= 256)
|
||||
-- delta filter: b[i] += b[i - dist] (1 <= dist <= 256)
|
||||
function Filters.delta(b: buffer, o: number, n: number, dist: number)
|
||||
for i = dist, n - 1 do
|
||||
writeu8(b, o + i, band(readu8(b, o + i) + readu8(b, o + i - dist), 255))
|
||||
|
||||
@@ -1,21 +1,7 @@
|
||||
--!strict
|
||||
-- codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3):
|
||||
-- archive/xz, archive/7z (and anything else holding LZMA data) build on it. Decode only.
|
||||
-- Written from the LZMA specification (LzmaSpec.cpp, Igor Pavlov, public domain) and the xz file format specification
|
||||
-- 1.2 (Lasse Collin / Igor Pavlov, public domain); the BCJ filters follow xz-embedded (public domain).
|
||||
--
|
||||
-- local Lzma = require("@rosetta/codecs/compress/Lzma")
|
||||
-- local out, e = Lzma.lzma(buf, off, len, props, unpackSize?, opts?) -- raw LZMA; props = 5-byte buffer / string
|
||||
-- -- or { lc, lp, pb, dictSize }
|
||||
-- local out, e = Lzma.lzma2(buf, off, len, dictSize?, unpackSize?, opts?) -- raw LZMA2 chunks
|
||||
-- local out, e = Lzma.alone(buf, off?, len?, opts?) -- a .lzma file (13-byte header)
|
||||
-- local out, e = Lzma.xz(buf, off?, len?, opts?) -- a .xz file (all streams concatenated)
|
||||
-- Lzma.filter(id, buf, off, len, props?) -- BCJ / delta decode in place (7z)
|
||||
--
|
||||
-- Each returns buffer, consumedEnd (the input offset just past what was decoded) | nil, Err. opts.maxBytes (default
|
||||
-- 2^30) bounds the output (Err.LIMIT). xz: every stream, block, index and footer is parsed and checked; check types
|
||||
-- none / CRC-32 / CRC-64 are verified, SHA-256 is skipped (not verified). xz filters: LZMA2, delta, x86, PowerPC,
|
||||
-- ARM, ARM-Thumb, SPARC, ARM64; IA-64 and RISC-V are Err.UNSUPPORTED. Never throws.
|
||||
-- codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container.
|
||||
-- From LzmaSpec.cpp (Igor Pavlov) and the xz file format specification 1.2 (Lasse Collin / Igor Pavlov), both public
|
||||
-- domain; the BCJ filters follow xz-embedded (public domain).
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Crc32 = require("@rosetta/core/Crc32")
|
||||
@@ -30,7 +16,7 @@ local Lzma = {}
|
||||
local DEFAULT_MAX = 2 ^ 30
|
||||
|
||||
export type Options = {
|
||||
maxBytes: number?, -- refuse output larger than this (default 2^30)
|
||||
maxBytes: number?,
|
||||
}
|
||||
export type Props = { lc: number, lp: number, pb: number, dictSize: number? }
|
||||
|
||||
@@ -42,7 +28,6 @@ local function maxOf(opts: Options?): number
|
||||
return if type(m) == "number" and m >= 0 then m else DEFAULT_MAX
|
||||
end
|
||||
|
||||
-- a decoder message -> Err
|
||||
local function fail(msg: any, at: number?): Err.Err
|
||||
local s = tostring(msg)
|
||||
local code = Err.CORRUPT
|
||||
@@ -54,7 +39,6 @@ local function fail(msg: any, at: number?): Err.Err
|
||||
return Err.new(code, s, at)
|
||||
end
|
||||
|
||||
-- props byte -> lc, lp, pb | nil
|
||||
local function propsByte(d: number): (number?, number, number)
|
||||
if d >= 225 then
|
||||
return nil, 0, 0
|
||||
@@ -63,8 +47,6 @@ local function propsByte(d: number): (number?, number, number)
|
||||
end
|
||||
Lzma.propsByte = propsByte
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ LZMA
|
||||
-- decodeLzma(st, b, o, e, unpackSize?) -> consumedEnd | nil, Err: one raw LZMA stream into st (props set)
|
||||
local function decodeLzma(st: Decode.State, b: buffer, o: number, e: number, unpackSize: number?): (number?, Err.Err?)
|
||||
local ip, ierr = Decode.rcInit(st, b, o, e)
|
||||
if not ip then
|
||||
@@ -87,7 +69,6 @@ local function decodeLzma(st: Decode.State, b: buffer, o: number, e: number, unp
|
||||
return res :: number, nil
|
||||
end
|
||||
|
||||
-- lzma(buf, offset, length, props, unpackSize?, opts?) -> buffer, consumedEnd | nil, Err
|
||||
function Lzma.lzma(buf: buffer | string, offset: number?, length: number?, props: any, unpackSize: number?, opts: Options?): (buffer?, any)
|
||||
local b, o, l, aerr = args("Lzma.lzma", buf, offset, length)
|
||||
if not b then
|
||||
@@ -125,7 +106,7 @@ function Lzma.lzma(buf: buffer | string, offset: number?, length: number?, props
|
||||
return Decode.finish(st), consumed
|
||||
end
|
||||
|
||||
-- alone(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err: a .lzma file (props, dict size, u64 size)
|
||||
-- .lzma file: props byte, dict size, u64 unpacked size
|
||||
function Lzma.alone(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any)
|
||||
local b, o, l, aerr = args("Lzma.alone", buf, offset, length)
|
||||
if not b then
|
||||
@@ -145,8 +126,6 @@ function Lzma.alone(buf: buffer | string, offset: number?, length: number?, opts
|
||||
return Lzma.lzma(b, o + 13, l - 13, buffer.fromstring(buffer.readstring(b, o, 1)), size, opts)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ LZMA2
|
||||
-- decodeLzma2(st, b, o, e) -> consumedEnd | nil, Err: LZMA2 chunks up to the end-of-stream byte
|
||||
local function decodeLzma2(st: Decode.State, b: buffer, o: number, e: number): (number?, Err.Err?)
|
||||
local p = o
|
||||
local needDict, needProps = true, true
|
||||
@@ -234,7 +213,6 @@ local function decodeLzma2(st: Decode.State, b: buffer, o: number, e: number): (
|
||||
end
|
||||
end
|
||||
|
||||
-- lzma2(buf, offset?, length?, dictSize?, unpackSize?, opts?) -> buffer, consumedEnd | nil, Err
|
||||
function Lzma.lzma2(buf: buffer | string, offset: number?, length: number?, _dictSize: number?, unpackSize: number?, opts: Options?): (buffer?, any)
|
||||
local b, o, l, aerr = args("Lzma.lzma2", buf, offset, length)
|
||||
if not b then
|
||||
@@ -252,7 +230,6 @@ function Lzma.lzma2(buf: buffer | string, offset: number?, length: number?, _dic
|
||||
return Decode.finish(st), consumed
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ filters
|
||||
-- filter ids (xz numbering; 7z's method ids map onto these in archive/7z)
|
||||
Lzma.FILTER = table.freeze({
|
||||
delta = 0x03,
|
||||
@@ -275,8 +252,7 @@ local BCJ: { [number]: (buffer, number, number, number) -> () } = {
|
||||
[0x0A] = Filters.arm64,
|
||||
}
|
||||
|
||||
-- filter(id, buf, offset, length, props?) -> true | nil, Err: decode a BCJ / delta filter in place. props: the
|
||||
-- filter's property bytes (a string or buffer: BCJ start offset u32le, delta distance - 1)
|
||||
-- filter properties: BCJ start offset u32le, delta distance - 1
|
||||
function Lzma.filter(id: number, b: buffer, o: number, n: number, props: any?): (boolean?, Err.Err?)
|
||||
local pb = toBuffer(props)
|
||||
local plen = if pb then buffer.len(pb) else 0
|
||||
@@ -301,11 +277,9 @@ function Lzma.filter(id: number, b: buffer, o: number, n: number, props: any?):
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ xz
|
||||
local XZ_MAGIC = "\253" .. "7zXZ\0"
|
||||
local CHECK_SIZE = { [0] = 0, 4, 4, 4, 8, 8, 8, 16, 16, 16, 32, 32, 32, 64, 64, 64 }
|
||||
|
||||
-- vli(b, p, e) -> value, next | nil
|
||||
local function vli(b: buffer, p: number, e: number): (number?, number)
|
||||
local v, mul = 0, 1
|
||||
for i = 0, 8 do
|
||||
@@ -330,7 +304,6 @@ local function crc(b: buffer, o: number, n: number): number
|
||||
return Crc32.raw(b, o, n)
|
||||
end
|
||||
|
||||
-- one xz stream at o -> next offset | nil, Err (blocks appended to st)
|
||||
local function xzStream(st: Decode.State, b: buffer, o: number, e: number): (number?, Err.Err?)
|
||||
if o + 12 > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "truncated xz stream header", o)
|
||||
@@ -521,7 +494,6 @@ local function xzStream(st: Decode.State, b: buffer, o: number, e: number): (num
|
||||
return q + 12, nil
|
||||
end
|
||||
|
||||
-- xz(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err: every stream (and stream padding) in the range
|
||||
function Lzma.xz(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any)
|
||||
local b, o, l, aerr = args("Lzma.xz", buf, offset, length)
|
||||
if not b then
|
||||
@@ -558,7 +530,6 @@ function Lzma.xz(buf: buffer | string, offset: number?, length: number?, opts: O
|
||||
return Decode.finish(st), p
|
||||
end
|
||||
|
||||
-- isXz(buf, offset?) -> true when the bytes start an xz stream
|
||||
function Lzma.isXz(b: buffer, o: number?): boolean
|
||||
local off = o or 0
|
||||
return off + 6 <= buffer.len(b) and buffer.readstring(b, off, 6) == XZ_MAGIC
|
||||
|
||||
@@ -1,25 +1,9 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and
|
||||
-- image/tiff build on it. New code (no port), written from the GIF89a spec (appendix F) and TIFF 6.0 section 13.
|
||||
-- gif LSB-first codes, a minimum code size 1..11 (2..8 in GIF), clear = 2^min, EOI = clear + 1, the code width
|
||||
-- grows when the next free code reaches 2^width (max 12 bits; a full table stays frozen until a clear).
|
||||
-- tiff MSB-first codes, 8-bit symbols, clear = 256, EOI = 257, "early change": the width grows one code
|
||||
-- earlier (next free code = 2^width - 1). Old-style (pre-6.0, LSB-first, no early change) TIFF LZW is
|
||||
-- detected by its first bytes (0x00 then an odd byte) and decoded too.
|
||||
-- zoo the gif layout with 8-bit symbols and codes up to 13 bits (Zoo archives' method 1; decode only).
|
||||
--
|
||||
-- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "gif", minCodeSize) -- bytes written
|
||||
-- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "tiff")
|
||||
-- local n, err = Lzw.decode(src, off, len, out, outOff, maxOut, "zoo")
|
||||
-- local codes = Lzw.encode(data, off, len, "gif", minCodeSize) -- buffer
|
||||
-- local codes = Lzw.encode(data, off, len, "tiff")
|
||||
--
|
||||
-- decode writes at most maxOut bytes at out[outOff ..] and returns how many it wrote; it stops at EOI, at the end of
|
||||
-- the input or when out is full. err is nil for a clean stream, "truncated" when the input ended without EOI, or
|
||||
-- "corrupt" for an impossible code (everything decoded up to it is kept). Never throws; the caller checks that
|
||||
-- [outOff, outOff + maxOut) lies inside out and [off, off + len) inside src (decode clamps both anyway).
|
||||
-- codecs/compress/Lzw: LZW decoder and encoder, from the GIF89a spec (appendix F) and TIFF 6.0 section 13 (new code).
|
||||
-- gif: LSB-first, clear = 2^min, EOI = clear + 1, width grows when the next code reaches 2^width (max 12, then frozen).
|
||||
-- tiff: MSB-first, clear = 256, EOI = 257, early change (at 2^width - 1). zoo (method 1): gif layout, up to 13 bits.
|
||||
local readu8, writeu8, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16
|
||||
local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift
|
||||
local blen = buffer.len
|
||||
@@ -29,14 +13,11 @@ local Lzw = {}
|
||||
local MAX_CODES = 4096 -- 12-bit codes (GIF, TIFF)
|
||||
local TABLE = 8192 -- the tables hold 13-bit codes (Zoo)
|
||||
|
||||
-- per-call tables (allocated once: decode / encode are not re-entrant across coroutines, but never yield)
|
||||
local prefix = buffer.create(TABLE * 2) -- u16: the code this entry extends
|
||||
local suffix = buffer.create(TABLE) -- u8: its last byte
|
||||
local first = buffer.create(TABLE) -- u8: its first byte
|
||||
local length = buffer.create(TABLE * 2) -- u16: its length
|
||||
local prefix = buffer.create(TABLE * 2)
|
||||
local suffix = buffer.create(TABLE)
|
||||
local first = buffer.create(TABLE)
|
||||
local length = buffer.create(TABLE * 2)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- writes the string of code c (length l) ending at out[o + l - 1]; clipped to [o, lim)
|
||||
local function emit(out: buffer, o: number, c: number, l: number, lim: number)
|
||||
local p = o + l - 1
|
||||
if p < lim then
|
||||
@@ -67,7 +48,7 @@ function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff:
|
||||
return 0, "corrupt"
|
||||
end
|
||||
local msb = variant == "tiff"
|
||||
local early = 0 -- 1 for TIFF's early change
|
||||
local early = 0
|
||||
local min = minCodeSize or 8
|
||||
local maxCodes, maxBits = MAX_CODES, 12
|
||||
if variant == "zoo" then
|
||||
@@ -101,7 +82,6 @@ function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff:
|
||||
local p = off
|
||||
local acc, nb = 0, 0
|
||||
while true do
|
||||
-- refill (at most 13 + 7 bits held: below 2^21)
|
||||
while nb < size do
|
||||
if p >= e then
|
||||
return o - outOff, "truncated"
|
||||
@@ -133,7 +113,7 @@ function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff:
|
||||
return o - outOff, nil
|
||||
else
|
||||
if o >= lim then
|
||||
return o - outOff, nil -- full: the rest (normally just EOI) is ignored
|
||||
return o - outOff, nil
|
||||
end
|
||||
if prev < 0 then
|
||||
if c >= clear then
|
||||
@@ -178,13 +158,10 @@ function Lzw.decode(src: buffer, off: number, len: number, out: buffer, outOff:
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local HASH = 8192 -- open addressing over (prefix << 8 | byte) keys: a power of two above 4096 entries
|
||||
local hkey = buffer.create(HASH * 4) -- i32 key + 1 (0 = empty)
|
||||
local hval = buffer.create(HASH * 2) -- u16 code
|
||||
local HASH = 8192
|
||||
local hkey = buffer.create(HASH * 4)
|
||||
local hval = buffer.create(HASH * 2)
|
||||
|
||||
-- encode(data, off, len, variant, minCodeSize?) -> the code stream (GIF: without the sub-block framing). Symbols in
|
||||
-- data must be below 2^minCodeSize (GIF; larger ones are masked) or bytes (TIFF).
|
||||
function Lzw.encode(data: buffer, off: number, len: number, variant: string, minCodeSize: number?): buffer
|
||||
local msb = variant == "tiff"
|
||||
local min = if msb then 8 else math.clamp(minCodeSize or 8, 1, 11)
|
||||
|
||||
@@ -1,19 +1,9 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/compress/Lzx: the LZX decoder as Microsoft Cabinet folders use it: windows of 2^15 .. 2^21 bytes,
|
||||
-- verbatim, aligned offset and uncompressed blocks (block sizes of 24 bits, blocks spanning frames), the main and
|
||||
-- length trees sent as deltas of the previous block's code lengths through a 20-symbol pre-tree (runs 17 / 18 / 19),
|
||||
-- the three repeated offsets R0..R2, the Intel E8 call translation header (applied to the first 32768 frames, on the
|
||||
-- output only), and the stream cut into frames of 32768 output bytes, each 16-bit aligned at its end; trees, offsets
|
||||
-- and the window persist across the frames (the CFDATA blocks) of a folder. Written from the specification
|
||||
-- (Microsoft's LZX data format documentation in the Cabinet SDK and the LZX sections of [MS-PATCH]); no code from
|
||||
-- libmspack. Not supported: LZX DELTA reference data and reset intervals (CHM / WIM variants).
|
||||
--
|
||||
-- local out, err = Lzx.decode(src, offset, length, outSize, windowBits) -- buffer | nil, message
|
||||
--
|
||||
-- src[offset, offset + length) is the folder's compressed data (the CFDATA payloads concatenated), outSize its exact
|
||||
-- uncompressed size. Never throws: bad or truncated data returns nil, message.
|
||||
-- codecs/compress/Lzx: the LZX decoder for Microsoft Cabinet folders (windows of 2^15 .. 2^21 bytes).
|
||||
-- Written from Microsoft's LZX data format documentation (Cabinet SDK) and [MS-PATCH]; no code from libmspack.
|
||||
-- Frames of 32768 output bytes, 16-bit aligned at their ends; trees, R0..R2 and the window persist across a folder.
|
||||
local Huffman = require("@rosetta/codecs/entropy/Huffman")
|
||||
|
||||
local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift
|
||||
@@ -43,9 +33,7 @@ do
|
||||
end
|
||||
local SLOTS: { [number]: number } = { [15] = 30, [16] = 32, [17] = 34, [18] = 36, [19] = 38, [20] = 42, [21] = 50 }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ bit reader
|
||||
-- 16-bit little-endian words read most significant bit first; bb holds cnt bits left aligned (cnt <= 32). Past the
|
||||
-- end, zero words are read and over counts their bits.
|
||||
-- 16-bit little-endian words, read most significant bit first
|
||||
type State = { src: buffer, pos: number, stop: number, bb: number, cnt: number, over: number }
|
||||
|
||||
local function refill(s: State)
|
||||
@@ -67,7 +55,6 @@ local function refill(s: State)
|
||||
end
|
||||
end
|
||||
|
||||
-- bits(s, n) -> the next n (1..17) bits
|
||||
local function bits(s: State, n: number): number
|
||||
if s.cnt < n then
|
||||
refill(s)
|
||||
@@ -78,7 +65,6 @@ local function bits(s: State, n: number): number
|
||||
return v
|
||||
end
|
||||
|
||||
-- sym(s, tab, P, S) -> the next symbol of an MSB Huffman table, -1 for an invalid code
|
||||
local function sym(s: State, tab: buffer, P: number, S: number): number
|
||||
if s.cnt < 16 then
|
||||
refill(s)
|
||||
@@ -100,7 +86,7 @@ local function sym(s: State, tab: buffer, P: number, S: number): number
|
||||
return rshift(e, 5)
|
||||
end
|
||||
|
||||
-- readLens: the code lengths lens[first, last) as deltas of their previous values, through a fresh pre-tree
|
||||
-- code lengths as deltas of their previous values, through a fresh 20-symbol pre-tree (runs 17 / 18 / 19)
|
||||
local function readLens(s: State, lens: buffer, first: number, last: number, pre: buffer, preLens: buffer): boolean
|
||||
for i = 0, 19 do
|
||||
writeu8(preLens, i, bits(s, 4))
|
||||
@@ -145,8 +131,7 @@ local function readLens(s: State, lens: buffer, first: number, last: number, pre
|
||||
return true
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- E8 translation of the decoded output, frame by frame (absolute call targets back to relative)
|
||||
-- E8 translation, frame by frame: absolute call targets back to relative
|
||||
local function translate(out: buffer, n: number, size: number)
|
||||
local base = 0
|
||||
local frame = 0
|
||||
@@ -199,7 +184,6 @@ function Lzx.decode(src: buffer, offset: number, length: number, outSize: number
|
||||
local frameEnd = math.min(op + FRAME, outSize)
|
||||
while op < frameEnd do
|
||||
if bremain == 0 then
|
||||
-- a new block
|
||||
if btype == 3 and band(bsize, 1) == 1 then
|
||||
s.pos += 1
|
||||
end
|
||||
@@ -283,7 +267,6 @@ function Lzx.decode(src: buffer, offset: number, length: number, outSize: number
|
||||
local aligned = btype == 2
|
||||
local start = op
|
||||
while op < runEnd do
|
||||
-- refill to at least 17 bits
|
||||
while cnt <= 16 do
|
||||
local w = 0
|
||||
if pos + 2 <= stop then
|
||||
|
||||
@@ -1,18 +1,12 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD / PSB RLE channels, IFF
|
||||
-- ByteRun1, ...): a header byte n < 128 copies n + 1 literal bytes, n > 128 repeats the next byte 257 - n times,
|
||||
-- 128 is a no-op. Decode and encode; moved here from image/tiff (TIFF and PSD both carried a decoder). Never throws.
|
||||
--
|
||||
-- local written, srcEnd, clean = PackBits.decode(src, p, limit, dst, d, n) -- up to n bytes into dst at d
|
||||
-- local packed = PackBits.encode(src, offset, length) -- a buffer (one row at a time)
|
||||
-- codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD RLE, IFF ByteRun1).
|
||||
-- Header byte n < 128 copies n + 1 literal bytes, n > 128 repeats the next byte 257 - n times, 128 is a no-op.
|
||||
local PackBits = {}
|
||||
|
||||
local readu8, writeu8 = buffer.readu8, buffer.writeu8
|
||||
|
||||
-- decode(src, p, limit, dst, d, n) -> bytes written (<= n), the source offset after the codes used, clean (false when
|
||||
-- the source ran out before n bytes or a run overflowed n: lenient callers keep what was written, strict ones fail)
|
||||
function PackBits.decode(src: buffer, p: number, limit: number, dst: buffer, d: number, n: number): (number, number, boolean)
|
||||
local o, lim = d, d + n
|
||||
local clean = true
|
||||
@@ -56,7 +50,6 @@ function PackBits.decode(src: buffer, p: number, limit: number, dst: buffer, d:
|
||||
return o - d, p, clean
|
||||
end
|
||||
|
||||
-- encode(src, offset, length) -> buffer: runs of 3+ equal bytes as repeats, the rest as literals (at most 128 each)
|
||||
function PackBits.encode(src: buffer, off: number, len: number): buffer
|
||||
local out = buffer.create(len + (len + 127) // 128 + 8)
|
||||
local o = 0
|
||||
|
||||
@@ -1,20 +1,9 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 with an adaptive arithmetic coder) as Microsoft
|
||||
-- Cabinet folders use it: windows of 2^10 .. 2^21 bytes; a 16-bit arithmetic decoder (H / L / C registers with
|
||||
-- underflow handling) over a most-significant-bit-first byte stream; eight adaptive frequency models (the
|
||||
-- 7-symbol selector, four 64-symbol literal models, the offset models for matches of 3, 4 and 5..259 bytes and the
|
||||
-- 27-symbol length model) whose cumulative frequencies grow by 8 per symbol and are rescaled above 3800 (halved, and
|
||||
-- every 50th time rebuilt from the frequencies and re-sorted); position and length footers read as raw bits from the
|
||||
-- same stream. Each CFDATA block is one frame (at most 32768 output bytes) that restarts the arithmetic coder; the
|
||||
-- models and the window persist across the frames of a folder. Written from the public descriptions of the format
|
||||
-- (the Quantum notes by Matthew Russotto and the cabinet documentation); no code from libmspack.
|
||||
--
|
||||
-- local out, err = Quantum.decode(src, blocks, outSize, windowBits) -- buffer | nil, message
|
||||
--
|
||||
-- blocks = { { at, len, size } }: each block's compressed bytes src[at, at + len) and its output size; outSize is
|
||||
-- their total. Never throws: bad or truncated data returns nil, message.
|
||||
-- codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 + adaptive arithmetic coder) for Cabinet folders.
|
||||
-- Written from Matthew Russotto's Quantum notes and the cabinet documentation; no code from libmspack. Frequencies grow
|
||||
-- by 8 and rescale above 3800 (halved; every 50th time rebuilt and re-sorted); each CFDATA frame restarts the coder.
|
||||
|
||||
local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
|
||||
local readu8, writeu8 = buffer.readu8, buffer.writeu8
|
||||
@@ -45,8 +34,7 @@ do
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ models
|
||||
-- an adaptive model: symbols sym[1..n] in their current order, cumulative frequencies cum[1..n + 1] (cum[n + 1] = 0)
|
||||
-- model: sym[1..n] in their current order, cumulative frequencies cum[1..n + 1] (cum[n + 1] = 0)
|
||||
type Model = { n: number, sym: { number }, cum: { number }, shifts: number }
|
||||
|
||||
local function model(first: number, n: number): Model
|
||||
@@ -92,8 +80,6 @@ local function rescale(m: Model)
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- the coder and bit reader of one frame
|
||||
type Coder = { src: buffer, pos: number, stop: number, acc: number, cnt: number, over: number, H: number, L: number, C: number, bad: boolean }
|
||||
|
||||
local function bit(c: Coder): number
|
||||
@@ -112,7 +98,6 @@ local function bit(c: Coder): number
|
||||
return band(rshift(c.acc, c.cnt), 1)
|
||||
end
|
||||
|
||||
-- raw(c, n) -> the next n (0..19) bits, most significant first
|
||||
local function raw(c: Coder, n: number): number
|
||||
local v = 0
|
||||
for _ = 1, n do
|
||||
@@ -127,7 +112,6 @@ local function symbol(c: Coder, m: Model): number
|
||||
local range = H - L + 1
|
||||
local total = cum[1]
|
||||
if range <= 0 or C < L or C > H then
|
||||
-- only corrupt registers get here (the decoder keeps L <= C <= H)
|
||||
c.bad = true
|
||||
return 0
|
||||
end
|
||||
|
||||
@@ -1,24 +1,16 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/compress/UnixCompress: the LZW of Unix compress (.Z files: magic 1F 9D, a flags byte with the maximum code
|
||||
-- width 9..16 and the block mode bit), decode and encode. A codec (layer 3): archive/z builds on it. Codes are
|
||||
-- LSB-first, 9 bits wide at the start; the width grows when the next free code passes 2^width - 1 (up to the
|
||||
-- maximum), and in block mode code 256 clears the table. compress writes codes in groups of eight: when the width
|
||||
-- changes or a CLEAR is read, the rest of the current group (counted from the previous change) is skipped. The encoder
|
||||
-- reproduces ncompress 5.0 bit for bit: greedy longest match, a full table frozen until the compression ratio checked
|
||||
-- every 10000 input bytes drops, then a CLEAR. Written from the ncompress sources (public domain, The Unlicense: read
|
||||
-- for the format and the encoder's ratio check; licenses/ncompress-UNLICENSE.txt). Never throws.
|
||||
--
|
||||
-- local out, err = UnixCompress.decompress(buf, offset?, length?, { maxBytes = 2^28 }) -- a whole .Z file
|
||||
-- local z = UnixCompress.compress(buf, offset?, length?, { maxBits = 16 }) -- -> a .Z file
|
||||
-- codecs/compress/UnixCompress: the LZW of Unix compress (.Z: magic 1F 9D, a flags byte: max width 9..16, block mode).
|
||||
-- From the ncompress sources (public domain: licenses/ncompress-UNLICENSE.txt); the encoder matches ncompress 5.0.
|
||||
-- LSB-first codes from 9 bits; block mode code 256 clears; a width change or CLEAR skips the rest of the 8-code group.
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
|
||||
local UnixCompress = {}
|
||||
|
||||
export type DecodeOptions = { maxBytes: number? } -- refuse output larger than this (default 2^30)
|
||||
export type EncodeOptions = { maxBits: number? } -- 9..16, default 16
|
||||
export type DecodeOptions = { maxBytes: number? }
|
||||
export type EncodeOptions = { maxBits: number? }
|
||||
|
||||
local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
|
||||
local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift
|
||||
@@ -27,14 +19,11 @@ local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
|
||||
local MAXCODES = 65536
|
||||
local CHECK_GAP = 10000
|
||||
|
||||
-- decoder tables (per call state lives in locals; the tables are reused: decode never yields)
|
||||
local prefix = bcreate(MAXCODES * 4) -- u32: the code an entry extends
|
||||
local suffix = bcreate(MAXCODES) -- u8: its last byte
|
||||
local first = bcreate(MAXCODES) -- u8: its first byte
|
||||
local length = bcreate(MAXCODES * 4) -- u32: its length
|
||||
local prefix = bcreate(MAXCODES * 4)
|
||||
local suffix = bcreate(MAXCODES)
|
||||
local first = bcreate(MAXCODES)
|
||||
local length = bcreate(MAXCODES * 4)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- decompress(buf, offset?, length?, opts?) -> buffer | nil, Err
|
||||
function UnixCompress.decompress(buf: buffer | string, offset: number?, len: number?, opts: DecodeOptions?): (buffer?, Err.Err?)
|
||||
local b, o, n, aerr = Bytes.span("UnixCompress.decompress", buf, offset, len)
|
||||
if not b then
|
||||
@@ -68,8 +57,8 @@ function UnixCompress.decompress(buf: buffer | string, offset: number?, len: num
|
||||
local op = 0
|
||||
local totalBits = (n - 3) * 8
|
||||
local base = o + 3
|
||||
local pos = 0 -- bit position from the first code
|
||||
local gbase = 0 -- where the current group sequence starts
|
||||
local pos = 0
|
||||
local gbase = 0
|
||||
local nbits = 9
|
||||
local mask = 511
|
||||
local maxcode = 511
|
||||
@@ -85,7 +74,6 @@ function UnixCompress.decompress(buf: buffer | string, offset: number?, len: num
|
||||
mask = lshift(1, nbits) - 1
|
||||
continue
|
||||
end
|
||||
-- the code: up to 23 bits from three bytes
|
||||
local q = base + rshift(pos, 3)
|
||||
local acc = readu8(b, q)
|
||||
if q + 1 < o + n then
|
||||
@@ -157,12 +145,10 @@ function UnixCompress.decompress(buf: buffer | string, offset: number?, len: num
|
||||
return res, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local HSIZE = 1 * 131072 -- open addressing over (prefix << 8 | byte) + 1 keys: twice the 65536 entries
|
||||
local HSIZE = 1 * 131072
|
||||
local hkey = bcreate(HSIZE * 4)
|
||||
local hval = bcreate(HSIZE * 4)
|
||||
|
||||
-- compress(buf, offset?, length?, opts?) -> a .Z file (block mode) | nil, Err
|
||||
function UnixCompress.compress(buf: buffer | string, offset: number?, len: number?, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local b, o, n, aerr = Bytes.span("UnixCompress.compress", buf, offset, len)
|
||||
if not b then
|
||||
@@ -172,7 +158,6 @@ function UnixCompress.compress(buf: buffer | string, offset: number?, len: numbe
|
||||
if type(maxbits) ~= "number" or maxbits < 9 or maxbits > 16 or maxbits % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "maxBits must be 9..16")
|
||||
end
|
||||
-- at most 17 bits per input byte, plus group padding (< one group per width change / clear)
|
||||
local cap = 3 + n * 2 + 64
|
||||
local out = bcreate(cap)
|
||||
writeu8(out, 0, 0x1F)
|
||||
@@ -180,7 +165,7 @@ function UnixCompress.compress(buf: buffer | string, offset: number?, len: numbe
|
||||
writeu8(out, 2, bor(maxbits, 0x80))
|
||||
local outbits = 24
|
||||
local boff = 24
|
||||
local acc, nb = 0, 0 -- pending bits not yet written (below 2^24)
|
||||
local acc, nb = 0, 0
|
||||
local nbits = 9
|
||||
local extcode = 513
|
||||
local maxmax = lshift(1, maxbits)
|
||||
@@ -290,7 +275,6 @@ function UnixCompress.compress(buf: buffer | string, offset: number?, len: numbe
|
||||
checks(i - o)
|
||||
end
|
||||
if rshift(outbits, 3) + 8 > cap then
|
||||
-- grow (rare: only incompressible input passes 2 bytes per byte)
|
||||
local ncap = cap * 2
|
||||
local nbuf = bcreate(ncap)
|
||||
bcopy(nbuf, 0, out, 0, cap)
|
||||
@@ -310,7 +294,6 @@ function UnixCompress.compress(buf: buffer | string, offset: number?, len: numbe
|
||||
return res, nil
|
||||
end
|
||||
|
||||
-- isCompress(buf, offset?) -> true when the bytes at offset start a .Z file
|
||||
function UnixCompress.isCompress(b: buffer, o: number?): boolean
|
||||
local p = o or 0
|
||||
return p + 3 <= blen(b) and readu8(b, p) == 0x1F and readu8(b, p + 1) == 0x9D
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/compress/Xxh32: XXH32 of a buffer range (any seed), for the LZ4 frame format's header, block and content
|
||||
-- checksums. 32 x 32 -> 32 products split one operand into 16-bit limbs so every partial product is exact in a double.
|
||||
-- From the xxHash specification (Yann Collet, BSD-2); no code copied. Never throws (the range is clamped to the buffer).
|
||||
--
|
||||
-- local h = Xxh32.hash(buf, offset?, length?, seed?) -- a number in 0 .. 2^32 - 1
|
||||
-- codecs/compress/Xxh32: XXH32 for the LZ4 frame checksums, from the xxHash specification (Yann Collet, BSD-2).
|
||||
-- 32 x 32 -> 32 products split one operand into 16-bit limbs so every partial product is exact in a double.
|
||||
local Xxh32 = {}
|
||||
|
||||
local bxor, bor, lshift, rshift = bit32.bxor, bit32.bor, bit32.lshift, bit32.rshift
|
||||
@@ -14,7 +11,6 @@ local readu8, readu32 = buffer.readu8, buffer.readu32
|
||||
local T32 = 4294967296
|
||||
local P1, P2, P3, P4, P5 = 0x9E3779B1, 0x85EBCA77, 0xC2B2AE3D, 0x27D4EB2F, 0x165667B1
|
||||
|
||||
-- a * b mod 2^32 (a, b below 2^32)
|
||||
local function mul(a: number, b: number): number
|
||||
local a0 = a % 65536
|
||||
local a1 = (a - a0) / 65536
|
||||
@@ -29,7 +25,6 @@ local function round(acc: number, lane: number): number
|
||||
return mul(rotl((acc + mul(lane, P2)) % T32, 13), P1)
|
||||
end
|
||||
|
||||
-- hash(buf, offset?, length?, seed?) -> XXH32
|
||||
function Xxh32.hash(b: buffer, offset: number?, length: number?, seed: number?): number
|
||||
local n0 = buffer.len(b)
|
||||
local o = math.clamp(offset or 0, 0, n0)
|
||||
|
||||
@@ -1,16 +1,8 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/compress/Zstd/Decode: Zstandard frame decoder (RFC 8878), written from the specification (no code copied from the
|
||||
-- BSD reference implementation). Frames (any number, concatenated), skippable frames, raw / RLE / compressed blocks,
|
||||
-- Huffman literals (1 or 4 streams, new or repeated table), FSE sequence tables (predefined / RLE / compressed /
|
||||
-- repeat), repeat offsets, the XXH64 content checksum. Not supported: dictionaries (a non-zero dictionary ID).
|
||||
--
|
||||
-- The whole output lives in one buffer, so the window is the output itself (offsets are checked against the frame's
|
||||
-- start). Backward bitstreams are read through bit offsets: bits [o - n, o) of a stream come from one readu32 at
|
||||
-- byte (o - n) / 8, bits before the stream start read as zeros.
|
||||
--
|
||||
-- Nothing here throws on any input: every read is bounds-checked; failures return nil, code, message, offset.
|
||||
-- codecs/compress/Zstd/Decode: Zstandard frame decoder (RFC 8878), written from the specification (no reference code).
|
||||
-- Backward bitstreams: bits [o - n, o) come from one readu32 at byte (o - n) / 8; bits before the stream read as zeros.
|
||||
local Xxh64 = require("@rosetta/codecs/compress/Zstd/Xxh64")
|
||||
|
||||
local band, lshift, rshift = bit32.band, bit32.lshift, bit32.rshift
|
||||
@@ -22,7 +14,6 @@ local BLOCK_MAX = 131072
|
||||
|
||||
local Decode = {}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ tables
|
||||
-- literal length / match length codes: baseline, extra bits (index = code + 1)
|
||||
local LL_BASE = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 24, 28, 32, 40, 48, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536 }
|
||||
local LL_BITS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }
|
||||
@@ -41,7 +32,6 @@ local ML_DEFAULT = {
|
||||
}
|
||||
local OF_DEFAULT = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1 }
|
||||
|
||||
-- highest set bit of 1..2048
|
||||
local HB = table.create(2048, 0)
|
||||
do
|
||||
local v = 0
|
||||
@@ -53,8 +43,6 @@ do
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ bit readers
|
||||
-- backward stream starting at byte s: bits [o - n, o) (n <= 25), bits below 0 are zeros
|
||||
local function peek(b: buffer, s: number, o: number, n: number): number
|
||||
if n <= 0 then
|
||||
return 0
|
||||
@@ -82,7 +70,6 @@ local function peek(b: buffer, s: number, o: number, n: number): number
|
||||
return lshift(peek(b, s, o, o), -lo)
|
||||
end
|
||||
|
||||
-- the bit length of a backward stream [s, e) (up to its end marker), or -1 when the last byte is 0 / it is empty
|
||||
local function streamBits(b: buffer, s: number, e: number): number
|
||||
if e <= s then
|
||||
return -1
|
||||
@@ -94,7 +81,6 @@ local function streamBits(b: buffer, s: number, e: number): number
|
||||
return (e - 1 - s) * 8 + HB[last]
|
||||
end
|
||||
|
||||
-- forward stream: n (<= 24) bits at bit position bp from byte p; bytes at or past e read as zeros
|
||||
local function getF(b: buffer, p: number, e: number, bp: number, n: number): number
|
||||
local byte = p + rshift(bp, 3)
|
||||
local v = 0
|
||||
@@ -108,11 +94,10 @@ local function getF(b: buffer, p: number, e: number, bp: number, n: number): num
|
||||
return band(rshift(v, band(bp, 7)), lshift(1, n) - 1)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ FSE
|
||||
-- FSE decoding table entries (u32): symbol | nbBits << 8 | newStateBase << 16
|
||||
local symTmp = bcreate(512)
|
||||
|
||||
-- build(norm, nsym, al, t) -> true | nil, message. norm: { [symbol + 1] = normalized count (-1 = "less than 1") }
|
||||
-- normalized counts: { [symbol + 1] = count }, -1 = "less than 1" probability
|
||||
local function buildFse(norm: { number }, nsym: number, al: number, t: buffer): (boolean?, string?)
|
||||
local size = lshift(1, al)
|
||||
local high = size - 1
|
||||
@@ -166,7 +151,6 @@ local function buildFse(norm: { number }, nsym: number, al: number, t: buffer):
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- ncount(b, p, e, maxSym, maxAL, norm) -> al, bytesUsed, nsym | nil, message: an FSE table description
|
||||
local function ncount(b: buffer, p: number, e: number, maxSym: number, maxAL: number, norm: { number }): (number?, any, number?)
|
||||
if p >= e then
|
||||
return nil, "truncated FSE table"
|
||||
@@ -251,8 +235,7 @@ local function predefined(dist: { number }, al: number): buffer
|
||||
end
|
||||
local LL_PRE, ML_PRE, OF_PRE = predefined(LL_DEFAULT, 6), predefined(ML_DEFAULT, 6), predefined(OF_DEFAULT, 5)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ Huffman
|
||||
-- hufTable(b, p, e, st) -> bytesUsed | nil, message: a Huffman tree description into st.huf (u16: sym | nbBits << 8)
|
||||
-- Huffman table entry (u16): sym | nbBits << 8
|
||||
local weights = bcreate(256)
|
||||
local wfse = bcreate(64 * 4)
|
||||
local function hufTable(b: buffer, p: number, e: number, st: any): (number?, string?)
|
||||
@@ -380,7 +363,6 @@ local function hufTable(b: buffer, p: number, e: number, st: any): (number?, str
|
||||
return used, nil
|
||||
end
|
||||
|
||||
-- one Huffman stream [s, e) -> cnt literals at lit[dp] | nil, message
|
||||
local function hufStream(b: buffer, s: number, e: number, t: buffer, mb: number, lit: buffer, dp: number, cnt: number): string?
|
||||
local off = streamBits(b, s, e)
|
||||
if off < 0 then
|
||||
@@ -411,8 +393,6 @@ local function hufStream(b: buffer, s: number, e: number, t: buffer, mb: number,
|
||||
return nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ frames
|
||||
-- grow st.out to hold need bytes (doubling, capped at st.maxBytes): true | false (over the limit)
|
||||
local function grow(st: any, need: number): boolean
|
||||
if need > st.maxBytes then
|
||||
return false
|
||||
@@ -424,7 +404,6 @@ local function grow(st: any, need: number): boolean
|
||||
return true
|
||||
end
|
||||
|
||||
-- a compressed block [p, e): nil (ok) | code, message
|
||||
local function block(b: buffer, p: number, e: number, st: any): (string?, string?)
|
||||
-- literals section
|
||||
local b0 = readu8(b, p)
|
||||
@@ -759,7 +738,6 @@ local function block(b: buffer, p: number, e: number, st: any): (string?, string
|
||||
bfill(out, op, readu8(out, from), ml)
|
||||
op += ml
|
||||
else
|
||||
-- overlapping: copy in chunks of `offset` bytes (each chunk's source precedes its destination)
|
||||
local left = ml
|
||||
while left > 0 do
|
||||
local n = if left < offset then left else offset
|
||||
@@ -790,7 +768,6 @@ local function block(b: buffer, p: number, e: number, st: any): (string?, string
|
||||
return nil, nil
|
||||
end
|
||||
|
||||
-- decompress(b, start, stop, maxBytes, verify) -> out, length, consumedEnd | nil, code, message, offset
|
||||
function Decode.decompress(b: buffer, start: number, stop: number, maxBytes: number, verify: boolean): (buffer?, any, any, any)
|
||||
local st: any = {
|
||||
out = bcreate(math.min(maxBytes, math.max(4096, (stop - start) * 3))),
|
||||
@@ -903,7 +880,6 @@ function Decode.decompress(b: buffer, start: number, stop: number, maxBytes: num
|
||||
st.rep1, st.rep2, st.rep3 = 1, 4, 8
|
||||
st.hufBits = nil
|
||||
table.clear(st.tabs)
|
||||
-- blocks
|
||||
local last = false
|
||||
repeat
|
||||
if pos + 3 > stop then
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/compress/Zstd/Xxh64: XXH64 (seed 0) of a buffer range, computed on 32-bit halves held in doubles (Luau and LuaJIT have
|
||||
-- no 64-bit integers). 64 x 64 -> 64 products split the low operand into 16-bit limbs so every partial product is
|
||||
-- exact below 2^53. From the xxHash specification (Yann Collet, BSD-2); no code copied. zstd stores the low 32 bits
|
||||
-- of the hash as the frame content checksum. Never throws (the caller passes an in-range buffer slice).
|
||||
-- codecs/compress/Zstd/Xxh64: XXH64 (seed 0) on 32-bit halves, from the xxHash specification (Yann Collet, BSD-2).
|
||||
-- 64 x 64 -> 64 products split the low operand into 16-bit limbs so every partial product is exact below 2^53.
|
||||
local bor, bxor, lshift, rshift = bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
|
||||
local readu8, readu32 = buffer.readu8, buffer.readu32
|
||||
|
||||
@@ -16,7 +14,6 @@ local P3H, P3L = 0x165667B1, 0x9E3779F9
|
||||
local P4H, P4L = 0x85EBCA77, 0xC2B2AE63
|
||||
local P5H, P5L = 0x27D4EB2F, 0x165667C5
|
||||
|
||||
-- (ah, al) * (bh, bl) mod 2^64
|
||||
local function mul(ah: number, al: number, bh: number, bl: number): (number, number)
|
||||
local a0 = al % 65536
|
||||
local a1 = (al - a0) / 65536
|
||||
@@ -41,7 +38,6 @@ local function add(ah: number, al: number, bh: number, bl: number): (number, num
|
||||
return h % T32, l
|
||||
end
|
||||
|
||||
-- rotl by r in 1..31
|
||||
local function rotl(h: number, l: number, r: number): (number, number)
|
||||
return bor(lshift(h, r), rshift(l, 32 - r)), bor(lshift(l, r), rshift(h, 32 - r))
|
||||
end
|
||||
@@ -49,7 +45,7 @@ end
|
||||
local P1L0, P1L1 = P1L % 65536, P1L // 65536
|
||||
local P2L0, P2L1 = P2L % 65536, P2L // 65536
|
||||
|
||||
-- acc = rotl(acc + input * P2, 31) * P1, with both products written out (the hot path: 4 per 32 input bytes)
|
||||
-- round: acc = rotl(acc + input * P2, 31) * P1
|
||||
local function round(ah: number, al: number, ih: number, il: number): (number, number)
|
||||
local a0 = il % 65536
|
||||
local a1 = (il - a0) / 65536
|
||||
@@ -87,7 +83,6 @@ end
|
||||
|
||||
local Xxh64 = {}
|
||||
|
||||
-- hash(b, offset, length) -> hi, lo (the 64-bit hash as two unsigned 32-bit halves)
|
||||
function Xxh64.hash(b: buffer, offset: number, length: number): (number, number)
|
||||
local p = offset
|
||||
local e = offset + length
|
||||
|
||||
@@ -1,15 +1,5 @@
|
||||
--!strict
|
||||
-- codecs/compress/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd
|
||||
-- data build on it. Written from the specification. Supports every frame feature a dictionary-less stream uses:
|
||||
-- concatenated and skippable frames, raw / RLE / compressed blocks, Huffman literals (1 / 4 streams, repeated tables),
|
||||
-- predefined / RLE / compressed / repeated FSE tables, repeat offsets, the XXH64 content checksum (verified).
|
||||
-- Not supported: dictionaries (Err.UNSUPPORTED), compression.
|
||||
--
|
||||
-- local Zstd = require("@rosetta/codecs/compress/Zstd")
|
||||
-- local out, err = Zstd.decompress(buf) -- -> buffer, consumedEnd | nil, Err
|
||||
-- local out, err = Zstd.decompress(buf, off, len, { maxBytes = 2^24, verify = false })
|
||||
--
|
||||
-- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / UNSUPPORTED / LIMIT / ARG).
|
||||
-- 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")
|
||||
@@ -17,14 +7,13 @@ local Decode = require("@rosetta/codecs/compress/Zstd/Decode")
|
||||
local Zstd = {}
|
||||
|
||||
export type Options = {
|
||||
maxBytes: number?, -- refuse output larger than this (default 2^30)
|
||||
verify: boolean?, -- check the content checksum when a frame has one (default true)
|
||||
maxBytes: number?,
|
||||
verify: boolean?,
|
||||
}
|
||||
|
||||
-- magic numbers: a zstd frame, and skippable frames (0x184D2A50 .. 0x184D2A5F)
|
||||
Zstd.MAGIC = "\40\181\47\253"
|
||||
|
||||
-- isFrame(buf, offset?) -> true when a zstd (or skippable) frame starts there
|
||||
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
|
||||
@@ -34,8 +23,7 @@ function Zstd.isFrame(buf: buffer, offset: number?): boolean
|
||||
return m == 0xFD2FB528 or bit32.band(m, 0xFFFFFFF0) == 0x184D2A50
|
||||
end
|
||||
|
||||
-- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err. Every frame in the range is decoded
|
||||
-- and the outputs concatenated; data after the last frame that is not a frame is an error (as zstd -d does).
|
||||
-- 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
|
||||
@@ -58,7 +46,6 @@ function Zstd.decompress(buf: buffer | string, offset: number?, length: number?,
|
||||
return out, consumed
|
||||
end
|
||||
|
||||
-- xxh64(buf, offset?, length?) -> hi, lo: the XXH64 hash (seed 0) as two unsigned 32-bit halves
|
||||
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)
|
||||
|
||||
Reference in new issue
Block a user