ws-arch2-unix: codecs/compress/UnixCompress (.Z LZW decode + encode, bit-identical to ncompress 5.0: group padding on width changes / CLEAR, ratio-check clears) + archive/z (single-stream, .taz / .tZ -> .tar, writes ncompress's bytes), tests vs ncompress and gzip -d, bench lines
This commit is contained in:
1 parent
8b94584d0f
commit
6eadacce64
10 files changed
+690
-1
No files matched your search
@@ -58,6 +58,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
| archive | rpm | .rpm | yes | - | compressors: "gzip", "bzip2", "xz", "lzma", "zstd" | `tests/archive/rpm.luau` |
|
||||
| archive | tar | .tar | yes | yes | variants: "ustar", "pax", "gnu" | `tests/archive/tar.luau` |
|
||||
| archive | xz | .xz .txz .lzma | yes | - | stream: true, filters: "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" | `tests/archive/xz.luau` |
|
||||
| archive | z | .z .taz .tz | yes | yes | stream: true, bits: 9, 16 | `tests/archive/z.luau` |
|
||||
| archive | zip | .zip .wsz | yes | yes | methods: "store", "deflate", zip64: true | `tests/archive/zip.luau` |
|
||||
| archive | zst | .zst .tzst | yes | - | stream: true | `tests/archive/zst.luau` |
|
||||
| data | cbor | .cbor | yes | yes | binary: true, ordered: true, tags: true | `tests/data/cbor.luau` |
|
||||
@@ -110,6 +111,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
|
||||
- codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3):
|
||||
- codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and
|
||||
- codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD / PSB RLE channels, IFF
|
||||
- codecs/compress/UnixCompress: the LZW of Unix compress (.Z files: magic 1F 9D, a flags byte with the maximum code
|
||||
- codecs/compress/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd
|
||||
- **entropy**
|
||||
- codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders.
|
||||
|
||||
@@ -38,6 +38,7 @@
|
||||
| `tests/fixtures/vp8video/vp80-*.ivf` | the VP8 test vectors of the libvpx test data (vp80-00-comprehensive-001..018 and others) | WebM Project, BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) |
|
||||
| `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) |
|
||||
| `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data |
|
||||
| `src/Formats/codecs/compress/UnixCompress.luau` (the .Z format and the encoder's ratio check / CLEAR rule, read from compress.c; the code is new) | ncompress 5.0 | public domain (The Unlicense): [ncompress-UNLICENSE.txt](ncompress-UNLICENSE.txt) |
|
||||
|
||||
Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this
|
||||
folder (see docs/STYLE.md, "Absorbing an existing repo").
|
||||
@@ -0,0 +1,24 @@
|
||||
This is free and unencumbered software released into the public domain.
|
||||
|
||||
Anyone is free to copy, modify, publish, use, compile, sell, or
|
||||
distribute this software, either in source code form or as a compiled
|
||||
binary, for any purpose, commercial or non-commercial, and by any
|
||||
means.
|
||||
|
||||
In jurisdictions that recognize copyright laws, the author or authors
|
||||
of this software dedicate any and all copyright interest in the
|
||||
software to the public domain. We make this dedication for the benefit
|
||||
of the public at large and to the detriment of our heirs and
|
||||
successors. We intend this dedication to be an overt act of
|
||||
relinquishment in perpetuity of all present and future rights to this
|
||||
software under copyright law.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
For more information, please refer to <http://unlicense.org/>
|
||||
@@ -650,6 +650,18 @@ local list: { Entry } = {
|
||||
return require("@formats/archive/xz")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "z",
|
||||
category = "archive",
|
||||
path = "archive/z",
|
||||
extensions = { "z", "taz", "tz" },
|
||||
mime = { "application/x-compress" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/compress/UnixCompress", "containers/Archive", "containers/Tar" },
|
||||
caps = { decode = true, encode = true, stream = true, bits = { 9, 16 } },
|
||||
load = function()
|
||||
return require("@formats/archive/z")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "zip",
|
||||
category = "archive",
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
--!strict
|
||||
-- archive/z: Unix compress files (.Z: LZW, magic 1F 9D, 9..16-bit codes, block mode) as a single-stream Archive: one
|
||||
-- entry, named after the file without .Z (.taz / .tZ -> .tar), else "data"; meta.stream = true, so the api unwraps a
|
||||
-- .tar.Z into the tar. Writing: an Archive with one file entry (or a buffer / string) becomes that file compressed,
|
||||
-- byte for byte what ncompress writes; an Archive with several entries is written as a tar inside (a .tar.Z). The LZW is
|
||||
-- codecs/compress/UnixCompress. Not supported: pack (.z, 1F 1E) and compact (1F FF) files.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local UnixCompress = require("@formats/codecs/compress/UnixCompress")
|
||||
local Archive = require("@formats/containers/Archive")
|
||||
local Tar = require("@formats/containers/Tar")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Z = {
|
||||
name = "z",
|
||||
category = "archive",
|
||||
extensions = { "z", "taz", "tz" },
|
||||
mime = { "application/x-compress" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/compress/UnixCompress", "containers/Archive", "containers/Tar" },
|
||||
caps = { decode = true, encode = true, stream = true, bits = { 9, 16 } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse output larger than this (default 2^30)
|
||||
name: string?, -- the file name (the api passes it): names the entry
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
maxBits: number?, -- 9..16 (compress -b), default 16
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Z.sniff(r: Bytes.Reader): number
|
||||
if r:peek(2) ~= "\31\157" then
|
||||
return 0
|
||||
end
|
||||
local f = r:peekU8(2)
|
||||
return if f >= 0 and bit32.band(f, 0x60) == 0 and bit32.band(f, 0x1F) >= 9 and bit32.band(f, 0x1F) <= 16 then 1 else 0.3
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- the entry name: the file name without .Z; .taz / .tz name a tar
|
||||
local function entryName(opts: DecodeOptions): string
|
||||
local name = Archive.streamName(opts, { "z" })
|
||||
local stem, ext = string.match(name, "^(.+)%.(%w+)$")
|
||||
if stem and ext and (string.lower(ext) == "taz" or string.lower(ext) == "tz") then
|
||||
return stem .. ".tar"
|
||||
end
|
||||
return name
|
||||
end
|
||||
|
||||
local function encode(value: any, opts: any?): (buffer?, Err.Err?)
|
||||
return Z.encode(value, opts)
|
||||
end
|
||||
|
||||
function Z.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local n = r.limit - r.base
|
||||
local out, err = UnixCompress.decompress(r.buf, r.base, n, o)
|
||||
if not out then
|
||||
return nil, err
|
||||
end
|
||||
local a = Archive.new("z", encode)
|
||||
a.meta.stream = true
|
||||
a.meta.source = { format = "z", maxBits = bit32.band(buffer.readu8(r.buf, r.base + 2), 0x1F), blockMode = bit32.band(buffer.readu8(r.buf, r.base + 2), 0x80) ~= 0 }
|
||||
Archive.put(a, {
|
||||
name = entryName(o),
|
||||
size = buffer.len(out),
|
||||
compressedSize = n,
|
||||
method = "lzw",
|
||||
dir = false,
|
||||
data = out,
|
||||
})
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- the data to compress: a buffer / string, an Archive's one file, or a tar of its entries
|
||||
local function payload(value: any): (buffer?, Err.Err?)
|
||||
if type(value) == "buffer" then
|
||||
return value, nil
|
||||
elseif type(value) == "string" then
|
||||
return buffer.fromstring(value), nil
|
||||
end
|
||||
local items = Archive.entries(value)
|
||||
if not items then
|
||||
return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string")
|
||||
end
|
||||
if #items == 1 and not items[1].entry.dir then
|
||||
return items[1].read()
|
||||
end
|
||||
local list = {}
|
||||
for _, it in items do
|
||||
local e: any = it.entry
|
||||
local data: buffer? = nil
|
||||
if not e.dir and (e.type == nil or e.type == "0") then
|
||||
local b, err = it.read()
|
||||
if not b then
|
||||
return nil, err
|
||||
end
|
||||
data = b
|
||||
end
|
||||
table.insert(list, { name = e.name, data = data, dir = e.dir, type = e.type, link = e.link, mtime = e.mtime, mode = e.mode })
|
||||
end
|
||||
return Tar.write(list)
|
||||
end
|
||||
|
||||
function Z.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local data, err = payload(value)
|
||||
if not data then
|
||||
return nil, err
|
||||
end
|
||||
return UnixCompress.compress(data, 0, buffer.len(data), { maxBits = opts and opts.maxBits })
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new(data?, name?) -> a .Z Archive holding one entry
|
||||
function Z.new(data: (buffer | string)?, name: string?): any
|
||||
local a = Archive.new("z", encode)
|
||||
a.meta.stream = true
|
||||
a.meta.source = { format = "z" }
|
||||
if data then
|
||||
a:add(name or "data", data)
|
||||
end
|
||||
return a
|
||||
end
|
||||
|
||||
return Z
|
||||
@@ -0,0 +1,319 @@
|
||||
--!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
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/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
|
||||
|
||||
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
|
||||
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
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ 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
|
||||
return nil, aerr
|
||||
end
|
||||
local maxBytes = (opts and opts.maxBytes) or 2 ^ 30
|
||||
if n < 3 then
|
||||
return nil, Err.new(Err.TRUNCATED, "header past the end", o)
|
||||
end
|
||||
if readu8(b, o) ~= 0x1F or readu8(b, o + 1) ~= 0x9D then
|
||||
return nil, Err.new(Err.CORRUPT, "bad magic", o)
|
||||
end
|
||||
local flags = readu8(b, o + 2)
|
||||
local maxbits = band(flags, 0x1F)
|
||||
local block = band(flags, 0x80) ~= 0
|
||||
if maxbits < 9 or maxbits > 16 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "maximum code width " .. maxbits, o + 2)
|
||||
end
|
||||
if band(flags, 0x60) ~= 0 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "reserved flag bits set", o + 2)
|
||||
end
|
||||
local maxmax = lshift(1, maxbits)
|
||||
for i = 0, 255 do
|
||||
writeu32(prefix, i * 4, 0)
|
||||
writeu8(suffix, i, i)
|
||||
writeu8(first, i, i)
|
||||
writeu32(length, i * 4, 1)
|
||||
end
|
||||
local cap = math.min(math.max(n * 3, 1024), maxBytes)
|
||||
local out = bcreate(cap)
|
||||
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 nbits = 9
|
||||
local mask = 511
|
||||
local maxcode = 511
|
||||
local freeEnt = if block then 257 else 256
|
||||
local prev = -1
|
||||
while pos + nbits <= totalBits do
|
||||
if freeEnt > maxcode then
|
||||
local g = nbits * 8
|
||||
pos = gbase + (pos - gbase + g - 1) // g * g
|
||||
gbase = pos
|
||||
nbits += 1
|
||||
maxcode = if nbits == maxbits then maxmax else lshift(1, nbits) - 1
|
||||
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
|
||||
acc = bor(acc, lshift(readu8(b, q + 1), 8))
|
||||
end
|
||||
if q + 2 < o + n then
|
||||
acc = bor(acc, lshift(readu8(b, q + 2), 16))
|
||||
end
|
||||
local c = band(rshift(acc, band(pos, 7)), mask)
|
||||
pos += nbits
|
||||
if c == 256 and block then
|
||||
local g = nbits * 8
|
||||
pos = gbase + (pos - gbase + g - 1) // g * g
|
||||
gbase = pos
|
||||
nbits = 9
|
||||
mask = 511
|
||||
maxcode = 511
|
||||
freeEnt = 257
|
||||
prev = -1
|
||||
continue
|
||||
end
|
||||
local l
|
||||
if prev < 0 then
|
||||
if c >= 256 then
|
||||
return nil, Err.new(Err.CORRUPT, "first code is not a literal", base + rshift(pos, 3))
|
||||
end
|
||||
l = 1
|
||||
elseif c < freeEnt then
|
||||
l = readu32(length, c * 4)
|
||||
elseif c == freeEnt then
|
||||
l = readu32(length, prev * 4) + 1
|
||||
else
|
||||
return nil, Err.new(Err.CORRUPT, "code past the table", base + rshift(pos, 3))
|
||||
end
|
||||
if op + l > cap then
|
||||
if op + l > maxBytes then
|
||||
return nil, Err.new(Err.LIMIT, "output over " .. maxBytes .. " bytes")
|
||||
end
|
||||
local ncap = math.min(math.max(cap * 2, op + l), maxBytes)
|
||||
local nb = bcreate(ncap)
|
||||
bcopy(nb, 0, out, 0, op)
|
||||
out, cap = nb, ncap
|
||||
end
|
||||
-- the new entry (prev + first byte of c's string) before the copy: KwKwK reads it
|
||||
if prev >= 0 and freeEnt < maxmax then
|
||||
local f = if c == freeEnt then readu8(first, prev) else readu8(first, c)
|
||||
writeu32(prefix, freeEnt * 4, prev)
|
||||
writeu8(suffix, freeEnt, f)
|
||||
writeu8(first, freeEnt, readu8(first, prev))
|
||||
writeu32(length, freeEnt * 4, readu32(length, prev * 4) + 1)
|
||||
freeEnt += 1
|
||||
elseif prev >= 0 then
|
||||
if c == freeEnt then
|
||||
return nil, Err.new(Err.CORRUPT, "code past the table", base + rshift(pos, 3))
|
||||
end
|
||||
end
|
||||
local p = op + l - 1
|
||||
local k = c
|
||||
while p >= op do
|
||||
writeu8(out, p, readu8(suffix, k))
|
||||
k = readu32(prefix, k * 4)
|
||||
p -= 1
|
||||
end
|
||||
op += l
|
||||
prev = c
|
||||
end
|
||||
local res = bcreate(op)
|
||||
bcopy(res, 0, out, 0, op)
|
||||
return res, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local HSIZE = 1 * 131072 -- open addressing over (prefix << 8 | byte) + 1 keys: twice the 65536 entries
|
||||
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
|
||||
return nil, aerr
|
||||
end
|
||||
local maxbits = (opts and opts.maxBits) or 16
|
||||
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)
|
||||
writeu8(out, 1, 0x9D)
|
||||
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 nbits = 9
|
||||
local extcode = 513
|
||||
local maxmax = lshift(1, maxbits)
|
||||
local stcode = true
|
||||
local freeEnt = 257
|
||||
local ratio = 0
|
||||
local checkpoint = CHECK_GAP
|
||||
buffer.fill(hkey, 0, 0, HSIZE * 4)
|
||||
local function put(code: number)
|
||||
acc = bor(acc, lshift(code, nb))
|
||||
nb += nbits
|
||||
outbits += nbits
|
||||
while nb >= 8 do
|
||||
local q = rshift(outbits - nb, 3)
|
||||
if q < cap then
|
||||
writeu8(out, q, band(acc, 255))
|
||||
end
|
||||
acc = rshift(acc, 8)
|
||||
nb -= 8
|
||||
end
|
||||
end
|
||||
local function align()
|
||||
-- round outbits up to a whole group of nbits-bit codes since boff; the skipped bits are zeros
|
||||
local g = nbits * 8
|
||||
local nbits2 = boff + (outbits - boff + g - 1) // g * g
|
||||
if nb > 0 then
|
||||
local q = rshift(outbits - nb, 3)
|
||||
if q < cap then
|
||||
writeu8(out, q, band(acc, 255))
|
||||
end
|
||||
end
|
||||
acc, nb = 0, 0
|
||||
outbits = nbits2
|
||||
boff = nbits2
|
||||
end
|
||||
if n == 0 then
|
||||
local res = bcreate(3)
|
||||
bcopy(res, 0, out, 0, 3)
|
||||
return res, nil
|
||||
end
|
||||
local ent = readu8(b, o)
|
||||
local e = o + n
|
||||
local i = o + 1
|
||||
-- checks happen with a one-byte current string, right after an output (and at the start)
|
||||
local function checks(consumed: number)
|
||||
if freeEnt >= extcode then
|
||||
if nbits < maxbits then
|
||||
align()
|
||||
nbits += 1
|
||||
extcode = if nbits < maxbits then lshift(1, nbits) + 1 else lshift(1, nbits)
|
||||
else
|
||||
extcode = math.huge
|
||||
stcode = false
|
||||
end
|
||||
end
|
||||
if not stcode and consumed >= checkpoint then
|
||||
checkpoint = consumed + CHECK_GAP
|
||||
local outBytes = rshift(outbits, 3)
|
||||
local rat
|
||||
if consumed > 0x7FFFFF then
|
||||
local d = rshift(outBytes, 8)
|
||||
rat = if d == 0 then 0x7FFFFFFF else consumed // d
|
||||
else
|
||||
rat = (consumed * 256) // outBytes
|
||||
end
|
||||
if rat >= ratio then
|
||||
ratio = rat
|
||||
else
|
||||
ratio = 0
|
||||
buffer.fill(hkey, 0, 0, HSIZE * 4)
|
||||
put(256)
|
||||
align()
|
||||
nbits = 9
|
||||
extcode = 513
|
||||
freeEnt = 257
|
||||
stcode = true
|
||||
end
|
||||
end
|
||||
end
|
||||
checks(1)
|
||||
while i < e do
|
||||
local c = readu8(b, i)
|
||||
i += 1
|
||||
local key = ent * 256 + c + 1
|
||||
local h = band(ent * 4099 + c * 131 + rshift(ent, 5), HSIZE - 1)
|
||||
local found = -1
|
||||
while true do
|
||||
local k = readu32(hkey, h * 4)
|
||||
if k == 0 then
|
||||
break
|
||||
elseif k == key then
|
||||
found = readu32(hval, h * 4)
|
||||
break
|
||||
end
|
||||
h = band(h + 1, HSIZE - 1)
|
||||
end
|
||||
if found >= 0 then
|
||||
ent = found
|
||||
else
|
||||
put(ent)
|
||||
if stcode then
|
||||
writeu32(hkey, h * 4, key)
|
||||
writeu32(hval, h * 4, freeEnt)
|
||||
freeEnt += 1
|
||||
end
|
||||
ent = c
|
||||
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)
|
||||
out, cap = nbuf, ncap
|
||||
end
|
||||
end
|
||||
put(ent)
|
||||
if nb > 0 then
|
||||
local q = rshift(outbits - nb, 3)
|
||||
if q < cap then
|
||||
writeu8(out, q, band(acc, 255))
|
||||
end
|
||||
end
|
||||
local size = rshift(outbits + 7, 3)
|
||||
local res = bcreate(size)
|
||||
bcopy(res, 0, out, 0, math.min(size, cap))
|
||||
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
|
||||
end
|
||||
|
||||
return UnixCompress
|
||||
@@ -0,0 +1,70 @@
|
||||
-- archive/z tests: .Z files from ncompress load as single-stream archives (entry names from the file name, .taz -> .tar),
|
||||
-- a .tar.Z unwraps to the tar through the api, writing gives ncompress's bytes (a buffer, a one-entry Archive) and a
|
||||
-- tar inside for several entries, conversions, errors, the fuzz pass. Fixtures: tools/fixtures/z.py.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
local Z = require("@formats/archive/z")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Fx = require("@tests/gen/z")
|
||||
|
||||
local t = T.suite("z")
|
||||
t:eq(Z.name, "z", "name")
|
||||
|
||||
local text = Fx.cases[3]
|
||||
do
|
||||
local a, err = Z.decode(Bytes.reader(buffer.fromstring(text.z)), { name = "notes.txt.Z" })
|
||||
t:check(a, "decode: " .. tostring(err))
|
||||
t:check(a.meta.stream, "single stream")
|
||||
t:eq(a:list()[1].name, "notes.txt", "entry named after the file")
|
||||
t:eq(a:list()[1].method, "lzw", "method")
|
||||
t:eq(buffer.tostring(a:read("notes.txt")), text.input, "data")
|
||||
t:eq(a.meta.source.maxBits, 16, "maxBits")
|
||||
t:eq(Z.decode(Bytes.reader(buffer.fromstring(text.z))):list()[1].name, "data", "no name: data")
|
||||
t:eq(F.detect(text.z), "z", "F.detect")
|
||||
t:eq(Z.decode(Bytes.reader(buffer.fromstring(text.z)), { name = "x.taz" }):list()[1].name, "x.tar", ".taz -> .tar")
|
||||
t:eq(Z.decode(Bytes.reader(buffer.fromstring(text.z)), { name = "x.tZ" }):list()[1].name, "x.tar", ".tZ -> .tar")
|
||||
end
|
||||
|
||||
-- the api: a .tar.Z is the tar inside
|
||||
do
|
||||
local a, err = F.load(Fx.tarZ, { name = "src.tar.Z" })
|
||||
t:check(a, "tar.Z: " .. tostring(err))
|
||||
t:eq(a.format, "tar", "tar.Z unwraps")
|
||||
t:eq(a.meta.compression, "z", "meta.compression")
|
||||
t:eq(#a:list(), #Fx.tarNames, "tar entries")
|
||||
local outer = F.load(Fx.tarZ, { name = "src.tar.Z", unwrap = false })
|
||||
t:eq(outer:list()[1].name, "src.tar", "unwrap = false")
|
||||
end
|
||||
|
||||
-- writing
|
||||
do
|
||||
local out = assert(F.save(text.input, nil, { format = "z" }))
|
||||
t:check(buffer.tostring(out) == text.z, "a string: ncompress's bytes")
|
||||
local one = Z.new(text.input, "t.txt")
|
||||
t:check(buffer.tostring(assert(one:write())) == text.z, "a one-entry archive: ncompress's bytes")
|
||||
local tar = F.format("tar").new()
|
||||
tar:add("a.txt", "alpha")
|
||||
tar:add("b.txt", "beta")
|
||||
local tz = assert(F.save(tar, nil, { format = "z" }))
|
||||
local back = F.load(tz)
|
||||
t:eq(back.format, "tar", "several entries: a tar inside")
|
||||
t:eq(buffer.tostring(back:read("b.txt")), "beta", "tar inside: data")
|
||||
local b10 = assert(Z.encode(Fx.cases[6].input, { maxBits = Fx.cases[6].bits }))
|
||||
t:check(buffer.tostring(b10) == Fx.cases[6].z, "maxBits option")
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local _, e1 = Z.decode(Bytes.reader(buffer.fromstring("\31\157")))
|
||||
t:check(e1 and e1.code == Err.TRUNCATED, "short")
|
||||
local _, e2 = Z.encode({ kind = "image" })
|
||||
t:check(e2 and e2.code == Err.ARG, "encode a non-archive")
|
||||
t:eq(Z.sniff(Bytes.reader(buffer.fromstring("\31\139\8"))), 0, "gzip is not .Z")
|
||||
end
|
||||
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Z.decode(Bytes.reader(b), { maxBytes = 2 ^ 22 })
|
||||
end, { text.z, Fx.tarZ }, { mutations = 40, keepHeader = 3 })
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,75 @@
|
||||
-- codecs/compress/UnixCompress tests: ncompress 5.0 files (widths 10..16, block mode, CLEAR codes after the ratio
|
||||
-- check, empty / one-byte / random inputs) decode to their inputs; compress() gives ncompress's bytes for the same input
|
||||
-- and width; non-block-mode streams; errors; the fuzz pass. Fixtures: tools/fixtures/z.py.
|
||||
local T = require("@tests/T")
|
||||
local UnixCompress = require("@formats/codecs/compress/UnixCompress")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Fx = require("@tests/gen/z")
|
||||
|
||||
local t = T.suite("unixcompress")
|
||||
|
||||
for _, c in Fx.cases do
|
||||
local out, err = UnixCompress.decompress(c.z)
|
||||
t:check(out, c.name .. ": decompress: " .. tostring(err))
|
||||
t:eq(buffer.len(out), #c.input, c.name .. ": size")
|
||||
t:eq(Crc32.of(out), Crc32.of(buffer.fromstring(c.input)), c.name .. ": data")
|
||||
local z, zerr = UnixCompress.compress(c.input, nil, nil, { maxBits = c.bits })
|
||||
t:check(z, c.name .. ": compress: " .. tostring(zerr))
|
||||
t:eq(buffer.len(z), #c.z, c.name .. ": compressed size = ncompress")
|
||||
t:check(buffer.tostring(z) == c.z, c.name .. ": bytes identical to ncompress -b " .. c.bits)
|
||||
t:note("%-12s %7d -> %7d bytes (-b %d)", c.name, #c.input, #c.z, c.bits)
|
||||
end
|
||||
|
||||
-- 9-bit codes, LSB first, after a .Z header with the given flags byte
|
||||
local function pack(flags: number, codes: { number }): buffer
|
||||
local acc, nb, bytes = 0, 0, { 0x1F, 0x9D, flags }
|
||||
for _, c in codes do
|
||||
acc += c * 2 ^ nb
|
||||
nb += 9
|
||||
while nb >= 8 do
|
||||
table.insert(bytes, acc % 256)
|
||||
acc = acc // 256
|
||||
nb -= 8
|
||||
end
|
||||
end
|
||||
if nb > 0 then
|
||||
table.insert(bytes, acc)
|
||||
end
|
||||
return T.bytes(bytes)
|
||||
end
|
||||
|
||||
-- a non-block-mode stream (no CLEAR code; 256 is the first table entry): "ABABABA"
|
||||
do
|
||||
local out = UnixCompress.decompress(pack(0x10, { 65, 66, 256, 258 }))
|
||||
t:eq(out and buffer.tostring(out), "ABABABA", "non-block mode")
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local _, e1 = UnixCompress.decompress("\31\157")
|
||||
t:check(e1 and e1.code == Err.TRUNCATED, "short header")
|
||||
local _, e2 = UnixCompress.decompress("\31\158\144")
|
||||
t:check(e2 and e2.code == Err.CORRUPT, "bad magic")
|
||||
local _, e3 = UnixCompress.decompress("\31\157\145")
|
||||
t:check(e3 and e3.code == Err.UNSUPPORTED, "17-bit codes")
|
||||
local _, e4 = UnixCompress.decompress(pack(0x90, { 65, 400 }))
|
||||
t:check(e4 and e4.code == Err.CORRUPT, "a code past the table: " .. tostring(e4))
|
||||
local _, e5 = UnixCompress.decompress(Fx.cases[5].z, nil, nil, { maxBytes = 1000 })
|
||||
t:check(e5 and e5.code == Err.LIMIT, "maxBytes")
|
||||
local _, e6 = UnixCompress.compress("x", nil, nil, { maxBits = 17 })
|
||||
t:check(e6 and e6.code == Err.ARG, "maxBits 17")
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for _, c in Fx.cases do
|
||||
if #c.z < 4000 and #c.z > 3 then
|
||||
table.insert(samples, c.z)
|
||||
end
|
||||
end
|
||||
table.insert(samples, string.sub(Fx.cases[#Fx.cases].z, 1, 3000))
|
||||
t:fuzz("decompress", function(b: buffer)
|
||||
return UnixCompress.decompress(b, nil, nil, { maxBytes = 2 ^ 22 })
|
||||
end, samples, { mutations = 40, keepHeader = 3 })
|
||||
|
||||
t:done()
|
||||
+13
-1
@@ -1,7 +1,7 @@
|
||||
-- Throughput (bash tools/bench.sh): codec MB/s under both runtimes. MB/s are of decompressed output, best of n runs.
|
||||
-- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus), tools/fixtures/png.py (1024 x 768 images), tools/fixtures/mp3.py,
|
||||
-- tools/fixtures/opus.py (3 s stereo files; MB/s of f32 output, 48 kHz stereo f32 is 0.384 MB/s of real time),
|
||||
-- tools/fixtures/flac.py; wav encodes / decodes a generated tone; zstd / brotli / bzip2 / lzma / lz4 (*_bench corpora), fonts
|
||||
-- tools/fixtures/flac.py; wav encodes / decodes a generated tone; zstd / brotli / bzip2 / lzma / lz4 (*_bench corpora), .Z (tools/fixtures/z.py), fonts
|
||||
-- (glyphs per second), json / xml / yaml, jpeg / gif / tiff / qoi / tga / pnm / hdr and ImageOps.
|
||||
local Deflate = require("@formats/codecs/compress/Deflate")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
@@ -267,6 +267,18 @@ do
|
||||
Bzip2.decompress(bz)
|
||||
end)
|
||||
end
|
||||
do
|
||||
local UnixCompress = require("@formats/codecs/compress/UnixCompress")
|
||||
local ZC = require("@tests/gen/z")
|
||||
local zc = ZC.cases[5] -- the 700 KB corpus, -b 16
|
||||
local zb, zi = buffer.fromstring(zc.z), buffer.fromstring(zc.input)
|
||||
bench(".Z decompress (lzw -b16)", 5, #zc.input, function()
|
||||
UnixCompress.decompress(zb)
|
||||
end)
|
||||
bench(".Z compress (lzw -b16)", 3, #zc.input, function()
|
||||
UnixCompress.compress(zi)
|
||||
end)
|
||||
end
|
||||
do
|
||||
local Lzma = require("@formats/codecs/compress/Lzma")
|
||||
local LB = require("@tests/gen/lzma_bench")
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
# .Z fixtures (tools/fixtures.py): Unix compress files written by ncompress 5.0 (nixpkgs#ncompress, `compress -c -f
|
||||
# -b N`) from a few inputs: empty, one byte, short text, a 700 KB word corpus with incompressible stretches (the 16-bit
|
||||
# table fills, the ratio check emits CLEAR codes), random bytes, and every width 10..16; a .tar.Z for the api's unwrap.
|
||||
# gzip -d reads each file too (its output must be the input: a second decoder agreeing on what ncompress wrote).
|
||||
# tests/gen/z.luau { cases = { { name, input, bits, z } }, tarZ = data, tarNames = { ... } }
|
||||
import io, subprocess, tarfile
|
||||
|
||||
|
||||
def compress(data, bits):
|
||||
return subprocess.run(["nix", "shell", "nixpkgs#ncompress", "-c", "compress", "-c", "-f", "-b", str(bits)], input=data,
|
||||
capture_output=True, check=True).stdout
|
||||
|
||||
|
||||
def corpus(rng, size):
|
||||
words = ["".join(rng.choice("abcdefghijklmnopqrstuvwxyz") for _ in range(rng.randint(2, 9))) for _ in range(3000)]
|
||||
out = bytearray()
|
||||
while len(out) < size:
|
||||
if rng.random() < 0.002:
|
||||
out += rng.randbytes(rng.randint(500, 4000)) # incompressible stretches: the ratio drops, CLEAR follows
|
||||
else:
|
||||
out += (" ".join(rng.choice(words) for _ in range(12)) + ".\n").encode()
|
||||
return bytes(out[:size])
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(23)
|
||||
big = corpus(rng, 700000)
|
||||
inputs = [("empty", b"", 16), ("one", b"A", 16), ("text", b"TOBEORNOTTOBEORTOBEORNOT#" * 40, 16),
|
||||
("random", rng.randbytes(30000), 16), ("corpus16", big, 16)]
|
||||
mid = big[:120000]
|
||||
for bits in range(10, 16): # (-b 9 output does not round-trip through ncompress or gzip: not a valid file)
|
||||
inputs.append(("corpus-b%d" % bits, mid, bits))
|
||||
cases = []
|
||||
for name, data, bits in inputs:
|
||||
z = compress(data, bits)
|
||||
back = subprocess.run(["nix", "shell", "nixpkgs#gzip", "-c", "gzip", "-d", "-c"], input=z, capture_output=True, check=True).stdout
|
||||
assert back == data, "gzip -d disagrees on " + name
|
||||
cases.append({"name": name, "input": data, "bits": bits, "z": z})
|
||||
b = io.BytesIO()
|
||||
with tarfile.open(fileobj=b, mode="w", format=tarfile.PAX_FORMAT) as t:
|
||||
for n, d in (("a.txt", b"alpha\n"), ("b/c.txt", b"gamma " * 100)):
|
||||
ti = tarfile.TarInfo(n)
|
||||
ti.size, ti.mtime = len(d), 1700000000
|
||||
t.addfile(ti, io.BytesIO(d))
|
||||
ctx.emit("z", {"cases": cases, "tarZ": compress(b.getvalue(), 16), "tarNames": ["a.txt", "b/c.txt"]})
|
||||
Reference in new issue
Block a user