merge ws/arch2-cab (archive/cab; codecs/compress/Lzx, Quantum; Deflate preset dictionary + mszip)
This commit is contained in:
commit
3e83879a6e
15 files changed
+2267
-5
No files matched your search
+27
-1
@@ -2,7 +2,7 @@
|
||||
-- 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), .Z (tools/fixtures/z.py), fonts
|
||||
-- (glyphs per second), json / xml / yaml, jpeg / gif / tiff / qoi / tga / pnm / hdr and ImageOps.
|
||||
-- (glyphs per second), cab (LZX / MSZIP / Quantum), 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")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
@@ -1190,6 +1190,32 @@ do
|
||||
end
|
||||
end
|
||||
end
|
||||
-- ws-arch2 cabinets: LZX (codecs/compress/Lzx), Quantum (codecs/compress/Quantum) and MSZIP folders of
|
||||
-- tools/fixtures/cab.py (MB/s of output; each run decodes the cabinet again, so the folder cache does not count)
|
||||
do
|
||||
local Cab = require("@formats/archive/cab")
|
||||
local CF = require("@tests/gen/cab")
|
||||
for _, kind in { "lzx", "quantum", "mszip" } do
|
||||
local datas, total = {}, 0
|
||||
for _, c in CF.cases do
|
||||
local a = Cab.decode(Bytes.reader(buffer.fromstring(c.data))) :: any
|
||||
if a and a.meta.folders[1].method == kind and #c.data > 20000 then
|
||||
table.insert(datas, buffer.fromstring(c.data))
|
||||
for _, e in a:list() do
|
||||
total += e.size
|
||||
end
|
||||
end
|
||||
end
|
||||
bench("cab " .. kind .. " (" .. #datas .. " cabinets)", 5, total, function()
|
||||
for _, d in datas do
|
||||
local a = Cab.decode(Bytes.reader(d)) :: any
|
||||
for _, e in a:list() do
|
||||
a:read(e.name)
|
||||
end
|
||||
end
|
||||
end)
|
||||
end
|
||||
end
|
||||
do
|
||||
-- Draco (codecs/model/Draco): the Stanford bunny (35k points, 69k faces, Edgebreaker valence, normals) and a UV
|
||||
-- sphere with seams; MB/s of decoded output (u32 indices + f32 attributes per point), plus triangles per second.
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
# A small LZX compressor for the cab fixtures (tools/fixtures/cab.py): no tool in nixpkgs writes LZX cabinets, so the
|
||||
# fixtures make them here and cabextract (the reference) must extract them to the original bytes before our decoder
|
||||
# is compared with its output. Written from the LZX format description (as codecs/compress/Lzx): verbatim, aligned
|
||||
# offset and uncompressed blocks of chosen sizes (spanning frames), delta-coded trees with pre-tree runs, repeated
|
||||
# offsets, the E8 translation, 32 KB frames aligned to 16 bits. Hash-chain matching; not tuned for ratio or speed.
|
||||
import heapq, random, struct
|
||||
|
||||
FRAME = 32768
|
||||
SLOTS = {15: 30, 16: 32, 17: 34, 18: 36, 19: 38, 20: 42, 21: 50}
|
||||
EXTRA = [0 if i < 4 else min(i // 2 - 1, 17) for i in range(51)]
|
||||
BASE = []
|
||||
_b = 0
|
||||
for _e in EXTRA:
|
||||
BASE.append(_b)
|
||||
_b += 1 << _e
|
||||
|
||||
|
||||
def slot_of(fo):
|
||||
s = 0
|
||||
while s + 1 < len(BASE) and BASE[s + 1] <= fo:
|
||||
s += 1
|
||||
return s
|
||||
|
||||
|
||||
def lengths(freqs, maxlen):
|
||||
"""length-limited Huffman code lengths (halving the frequencies until the code fits); every tree complete"""
|
||||
f = list(freqs)
|
||||
used = [i for i, x in enumerate(f) if x > 0]
|
||||
while len(used) < 2: # a complete code needs two symbols
|
||||
i = next(i for i in range(len(f)) if f[i] == 0)
|
||||
f[i] = 1
|
||||
used.append(i)
|
||||
while True:
|
||||
heap = [(f[i], i, (i,)) for i in used]
|
||||
heapq.heapify(heap)
|
||||
depth = {i: 0 for i in used}
|
||||
k = len(f)
|
||||
while len(heap) > 1:
|
||||
a = heapq.heappop(heap)
|
||||
b = heapq.heappop(heap)
|
||||
for s in a[2] + b[2]:
|
||||
depth[s] += 1
|
||||
heapq.heappush(heap, (a[0] + b[0], k, a[2] + b[2]))
|
||||
k += 1
|
||||
if max(depth.values()) <= maxlen:
|
||||
out = [0] * len(f)
|
||||
for s, d in depth.items():
|
||||
out[s] = d
|
||||
return out
|
||||
f = [(x + 1) // 2 if x else 0 for x in f]
|
||||
|
||||
|
||||
def codes(lens):
|
||||
"""canonical codes (MSB first)"""
|
||||
out = [0] * len(lens)
|
||||
code = 0
|
||||
for l in range(1, 17):
|
||||
for s, x in enumerate(lens):
|
||||
if x == l:
|
||||
out[s] = code
|
||||
code += 1
|
||||
code <<= 1
|
||||
return out
|
||||
|
||||
|
||||
class Bits:
|
||||
def __init__(self):
|
||||
self.out = bytearray()
|
||||
self.acc = 0
|
||||
self.n = 0
|
||||
|
||||
def put(self, v, n):
|
||||
for i in range(n - 1, -1, -1):
|
||||
self.acc = (self.acc << 1) | ((v >> i) & 1)
|
||||
self.n += 1
|
||||
if self.n == 16:
|
||||
self.out += struct.pack("<H", self.acc)
|
||||
self.acc, self.n = 0, 0
|
||||
|
||||
def align(self):
|
||||
if self.n:
|
||||
self.put(0, 16 - self.n)
|
||||
|
||||
def aligned(self):
|
||||
return self.n == 0
|
||||
|
||||
|
||||
def e8(data, size):
|
||||
"""the encoder's E8 translation (relative call targets to absolute), frame by frame"""
|
||||
d = bytearray(data)
|
||||
for base in range(0, min(len(d), FRAME * 32768), FRAME):
|
||||
fs = min(FRAME, len(d) - base)
|
||||
i, stop = base, base + fs - 10
|
||||
while i < stop:
|
||||
if d[i] == 0xE8:
|
||||
rel = struct.unpack_from("<i", d, i + 1)[0]
|
||||
if -i <= rel < size:
|
||||
struct.pack_into("<i", d, i + 1, rel + i if rel < size - i else rel - size)
|
||||
i += 5
|
||||
else:
|
||||
i += 1
|
||||
return bytes(d)
|
||||
|
||||
|
||||
def tokens(data, start, end, window, reps, rng, maxchain=24):
|
||||
"""LZ77 tokens of data[start:end) (literal ints, or (length, offset)); matches stay inside the 32 KB frame"""
|
||||
out = []
|
||||
head = {}
|
||||
prev = {}
|
||||
|
||||
def insert(p):
|
||||
if p + 3 <= len(data):
|
||||
k = data[p:p + 3]
|
||||
prev[p] = head.get(k)
|
||||
head[k] = p
|
||||
for p in range(max(0, start - 4096), start):
|
||||
insert(p)
|
||||
p = start
|
||||
r = list(reps)
|
||||
while p < end:
|
||||
limit = min(257, end - p, (p // FRAME + 1) * FRAME - p)
|
||||
best, boff = 0, 0
|
||||
if limit >= 2:
|
||||
for o in r: # repeated offsets first
|
||||
if o <= p:
|
||||
l = 0
|
||||
while l < limit and data[p + l] == data[p + l - o]:
|
||||
l += 1
|
||||
if l > best:
|
||||
best, boff = l, o
|
||||
if limit >= 3:
|
||||
q = head.get(data[p:p + 3])
|
||||
chain = 0
|
||||
while q is not None and chain < maxchain and p - q <= window - 3:
|
||||
l = 0
|
||||
while l < limit and data[q + l] == data[p + l]:
|
||||
l += 1
|
||||
if l > best + 1:
|
||||
best, boff = l, p - q
|
||||
q = prev.get(q)
|
||||
chain += 1
|
||||
if best >= 3 or (best == 2 and boff in r):
|
||||
out.append((best, boff))
|
||||
if boff == r[0]:
|
||||
pass
|
||||
elif boff == r[1]:
|
||||
r[0], r[1] = r[1], r[0]
|
||||
elif boff == r[2]:
|
||||
r[0], r[2] = r[2], r[0]
|
||||
else:
|
||||
r = [boff, r[0], r[1]]
|
||||
for k in range(best):
|
||||
insert(p + k)
|
||||
p += best
|
||||
else:
|
||||
out.append(data[p])
|
||||
insert(p)
|
||||
p += 1
|
||||
return out, r
|
||||
|
||||
|
||||
class Tree:
|
||||
"""code lengths persisting across blocks (the deltas' base)"""
|
||||
|
||||
def __init__(self, n):
|
||||
self.lens = [0] * n
|
||||
|
||||
|
||||
def pretree_items(prev, new, rng, runs):
|
||||
"""the pre-tree symbols ((sym, extra bits, nbits) or (19, ...)) that turn prev into new"""
|
||||
items = []
|
||||
x = 0
|
||||
n = len(new)
|
||||
while x < n:
|
||||
if runs and new[x] == 0:
|
||||
r = 0
|
||||
while x + r < n and new[x + r] == 0:
|
||||
r += 1
|
||||
if r >= 20:
|
||||
r = min(r, 51)
|
||||
items.append((18, r - 20, 5, None))
|
||||
x += r
|
||||
continue
|
||||
if r >= 4:
|
||||
r = min(r, 19)
|
||||
items.append((17, r - 4, 4, None))
|
||||
x += r
|
||||
continue
|
||||
if runs:
|
||||
r = 0
|
||||
while x + r < n and new[x + r] == new[x]:
|
||||
r += 1
|
||||
if r >= 4:
|
||||
r = min(r, 5)
|
||||
items.append((19, r - 4, 1, (prev[x] - new[x]) % 17))
|
||||
x += r
|
||||
continue
|
||||
items.append(((prev[x] - new[x]) % 17, 0, 0, None))
|
||||
x += 1
|
||||
return items
|
||||
|
||||
|
||||
def write_tree(bits, tree, first, last, new, rng):
|
||||
items = pretree_items(tree.lens[first:last], new, rng, runs=rng.random() < 0.9)
|
||||
freq = [0] * 20
|
||||
for s, _, _, d in items:
|
||||
freq[s] += 1
|
||||
if d is not None:
|
||||
freq[d] += 1
|
||||
pl = lengths(freq, 15)
|
||||
pc = codes(pl)
|
||||
for l in pl:
|
||||
bits.put(l, 4)
|
||||
for s, ex, nb, d in items:
|
||||
bits.put(pc[s], pl[s])
|
||||
if nb:
|
||||
bits.put(ex, nb)
|
||||
if d is not None:
|
||||
bits.put(pc[d], pl[d])
|
||||
tree.lens[first:last] = new
|
||||
|
||||
|
||||
def compress(data, wbits=16, e8size=0, seed=1, plan=None):
|
||||
"""data -> (LZX stream bytes, [compressed bytes per 32 KB frame]); plan: [(block type 1..3, size)] (default:
|
||||
random sizes and types)"""
|
||||
rng = random.Random(seed)
|
||||
window = 1 << wbits
|
||||
nslots = SLOTS[wbits]
|
||||
src = e8(data, e8size) if e8size else bytes(data)
|
||||
if plan is None:
|
||||
plan = []
|
||||
left = len(src)
|
||||
while left > 0:
|
||||
n = min(left, rng.choice([5000, 20000, 32768, 45000, 70000, 100000]))
|
||||
plan.append((rng.choice([1, 1, 2, 2, 3]) if n > 100 else 1, n))
|
||||
left -= n
|
||||
bits = Bits()
|
||||
frames = []
|
||||
frame_start = 0
|
||||
main = Tree(256 + 8 * nslots)
|
||||
length = Tree(249)
|
||||
reps = [1, 1, 1]
|
||||
pos = 0
|
||||
first = True
|
||||
|
||||
def frame_end_check(p):
|
||||
nonlocal frame_start
|
||||
if p % FRAME == 0 or p == len(src):
|
||||
bits.align()
|
||||
frames.append(len(bits.out) - frame_start)
|
||||
frame_start = len(bits.out)
|
||||
|
||||
for btype, size in plan:
|
||||
if first:
|
||||
if e8size:
|
||||
bits.put(1, 1)
|
||||
bits.put(e8size >> 16, 16)
|
||||
bits.put(e8size & 0xFFFF, 16)
|
||||
else:
|
||||
bits.put(0, 1)
|
||||
first = False
|
||||
bits.put(btype, 3)
|
||||
bits.put(size >> 8, 16)
|
||||
bits.put(size & 0xFF, 8)
|
||||
end = pos + size
|
||||
if btype == 3:
|
||||
if bits.aligned():
|
||||
bits.put(0, 16)
|
||||
bits.align()
|
||||
for r in reps:
|
||||
bits.out += struct.pack("<I", r)
|
||||
while pos < end:
|
||||
n = min(end, (pos // FRAME + 1) * FRAME) - pos
|
||||
bits.out += src[pos:pos + n]
|
||||
pos += n
|
||||
frame_end_check(pos)
|
||||
if size & 1:
|
||||
bits.out += b"\0"
|
||||
if pos % FRAME == 0 or pos == len(src): # the pad byte belongs to the frame just closed
|
||||
frames[-1] += 1
|
||||
frame_start += 1
|
||||
continue
|
||||
toks, newreps = tokens(src, pos, end, window, reps, rng)
|
||||
# symbols
|
||||
mf = [0] * (256 + 8 * nslots)
|
||||
lf = [0] * 249
|
||||
af = [0] * 8
|
||||
syms = []
|
||||
r = list(reps)
|
||||
for t in toks:
|
||||
if isinstance(t, int):
|
||||
mf[t] += 1
|
||||
syms.append((t,))
|
||||
continue
|
||||
l, o = t
|
||||
if o == r[0]:
|
||||
slot = 0
|
||||
elif o == r[1]:
|
||||
slot = 1
|
||||
r[0], r[1] = r[1], r[0]
|
||||
elif o == r[2]:
|
||||
slot = 2
|
||||
r[0], r[2] = r[2], r[0]
|
||||
else:
|
||||
slot = slot_of(o + 2)
|
||||
r = [o, r[0], r[1]]
|
||||
hdr = min(l - 2, 7)
|
||||
m = 256 + slot * 8 + hdr
|
||||
mf[m] += 1
|
||||
ls = l - 2 - 7 if hdr == 7 else None
|
||||
if ls is not None:
|
||||
lf[ls] += 1
|
||||
foot = None
|
||||
if slot >= 3:
|
||||
foot = o + 2 - BASE[slot]
|
||||
if btype == 2 and EXTRA[slot] >= 3:
|
||||
af[foot & 7] += 1
|
||||
syms.append((m, ls, slot, foot))
|
||||
assert r == newreps
|
||||
reps = newreps
|
||||
if btype == 2:
|
||||
al = lengths(af, 7)
|
||||
for x in al:
|
||||
bits.put(x, 3)
|
||||
ac = codes(al)
|
||||
ml = lengths(mf, 16)
|
||||
ll = lengths(lf, 16) if any(lf) or rng.random() < 0.5 else [0] * 249
|
||||
write_tree(bits, main, 0, 256, ml[:256], rng)
|
||||
write_tree(bits, main, 256, len(ml), ml[256:], rng)
|
||||
write_tree(bits, length, 0, 249, ll, rng)
|
||||
mc, lc = codes(ml), codes(ll)
|
||||
for t, s in zip(toks, syms):
|
||||
m = s[0]
|
||||
bits.put(mc[m], ml[m])
|
||||
if m < 256:
|
||||
pos += 1
|
||||
else:
|
||||
_, ls, slot, foot = s
|
||||
if ls is not None:
|
||||
bits.put(lc[ls], ll[ls])
|
||||
if slot >= 3:
|
||||
ex = EXTRA[slot]
|
||||
if btype == 2 and ex >= 3:
|
||||
if ex > 3:
|
||||
bits.put(foot >> 3, ex - 3)
|
||||
bits.put(ac[foot & 7], al[foot & 7])
|
||||
elif ex:
|
||||
bits.put(foot, ex)
|
||||
pos += t[0]
|
||||
frame_end_check(pos)
|
||||
return bytes(bits.out), frames
|
||||
@@ -0,0 +1,183 @@
|
||||
# A small Quantum compressor for the cab fixtures (tools/fixtures/cab.py): no tool in nixpkgs writes Quantum
|
||||
# cabinets, so the fixtures make them here and cabextract (the reference) must extract them to the original bytes
|
||||
# before our decoder is compared with its output. Written from the format description (as codecs/compress/Quantum):
|
||||
# the same adaptive models, a 16-bit arithmetic encoder with underflow bits (Witten / Neal / Cleary style), position /
|
||||
# length footers as raw bits placed where the decoder (16 code bits ahead) reads them, one frame per 32 KB block.
|
||||
FRAME = 32768
|
||||
PEXTRA = [0 if i < 4 else i // 2 - 1 for i in range(42)]
|
||||
PBASE = []
|
||||
_b = 0
|
||||
for _e in PEXTRA:
|
||||
PBASE.append(_b)
|
||||
_b += 1 << _e
|
||||
LEXTRA = [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]
|
||||
LBASE = []
|
||||
_b = 0
|
||||
for _e in LEXTRA:
|
||||
LBASE.append(_b)
|
||||
_b += 1 << _e
|
||||
|
||||
|
||||
class Model:
|
||||
def __init__(self, first, n):
|
||||
self.n = n
|
||||
self.sym = [first + i for i in range(n)]
|
||||
self.cum = [n - i for i in range(n)] + [0]
|
||||
self.shifts = 4
|
||||
|
||||
def update(self, i):
|
||||
"""after coding sym[i] (0-based)"""
|
||||
for k in range(i + 1):
|
||||
self.cum[k] += 8
|
||||
if self.cum[0] > 3800:
|
||||
self.rescale()
|
||||
|
||||
def rescale(self):
|
||||
n, cum, sym = self.n, self.cum, self.sym
|
||||
self.shifts -= 1
|
||||
if self.shifts:
|
||||
for i in range(n - 1, -1, -1):
|
||||
cum[i] >>= 1
|
||||
if cum[i] <= cum[i + 1]:
|
||||
cum[i] = cum[i + 1] + 1
|
||||
return
|
||||
self.shifts = 50
|
||||
for i in range(n):
|
||||
cum[i] = (cum[i] - cum[i + 1] + 1) >> 1
|
||||
for i in range(n - 1):
|
||||
for j in range(i + 1, n):
|
||||
if cum[i] < cum[j]:
|
||||
cum[i], cum[j] = cum[j], cum[i]
|
||||
sym[i], sym[j] = sym[j], sym[i]
|
||||
for i in range(n - 1, -1, -1):
|
||||
cum[i] += cum[i + 1]
|
||||
|
||||
|
||||
class Encoder:
|
||||
"""one frame: code bits (by shift position) and raw bit runs to insert at code positions"""
|
||||
|
||||
def __init__(self):
|
||||
self.H, self.L = 0xFFFF, 0
|
||||
self.code = []
|
||||
self.pending = 0
|
||||
self.shifts = 0
|
||||
self.raws = [] # (code position, value, nbits)
|
||||
|
||||
def emit(self, b):
|
||||
self.code.append(b)
|
||||
self.code.extend([1 - b] * self.pending)
|
||||
self.pending = 0
|
||||
|
||||
def encode(self, m, s):
|
||||
i = m.sym.index(s)
|
||||
rng = self.H - self.L + 1
|
||||
tot = m.cum[0]
|
||||
self.H = self.L + (m.cum[i] * rng) // tot - 1
|
||||
self.L = self.L + (m.cum[i + 1] * rng) // tot
|
||||
m.update(i)
|
||||
while True:
|
||||
if (self.L ^ self.H) & 0x8000 == 0:
|
||||
self.emit(self.H >> 15)
|
||||
elif (self.L & 0x4000) and not (self.H & 0x4000):
|
||||
self.pending += 1
|
||||
self.L &= 0x3FFF
|
||||
self.H |= 0x4000
|
||||
else:
|
||||
break
|
||||
self.L = (self.L << 1) & 0xFFFF
|
||||
self.H = ((self.H << 1) & 0xFFFF) | 1
|
||||
self.shifts += 1
|
||||
|
||||
def raw(self, v, n):
|
||||
if n:
|
||||
self.raws.append((16 + self.shifts, v, n))
|
||||
|
||||
def finish(self):
|
||||
"""the frame's bytes: flushed code with the raw runs merged in, zero padded"""
|
||||
self.pending += 1
|
||||
self.emit(0 if self.L < 0x4000 else 1)
|
||||
need = 16 + self.shifts
|
||||
code = self.code + [0] * max(0, need - len(self.code))
|
||||
bits = []
|
||||
p = 0
|
||||
for at, v, n in self.raws:
|
||||
bits.extend(code[p:at])
|
||||
p = at
|
||||
bits.extend((v >> (n - 1 - k)) & 1 for k in range(n))
|
||||
bits.extend(code[p:])
|
||||
bits.extend([0] * (-len(bits) % 8 + 16)) # byte padding and 2 zero bytes: the decoder's lookahead stays inside
|
||||
return bytes(int("".join(map(str, bits[i:i + 8])), 2) for i in range(0, len(bits), 8))
|
||||
|
||||
|
||||
def slot_of(off1):
|
||||
s = 0
|
||||
while s + 1 < len(PBASE) and PBASE[s + 1] <= off1:
|
||||
s += 1
|
||||
return s
|
||||
|
||||
|
||||
def compress(data, wbits=16, maxchain=24):
|
||||
"""data -> [frame bytes] (one per 32 KB block)"""
|
||||
window = 1 << wbits
|
||||
slots = wbits * 2
|
||||
sel = Model(0, 7)
|
||||
lit = [Model(0, 64), Model(64, 64), Model(128, 64), Model(192, 64)]
|
||||
m3, m4, m5, mlen = Model(0, min(slots, 24)), Model(0, min(slots, 36)), Model(0, slots), Model(0, 27)
|
||||
lim3, lim4 = PBASE[m3.n - 1] + (1 << PEXTRA[m3.n - 1]), PBASE[m4.n - 1] + (1 << PEXTRA[m4.n - 1])
|
||||
limw = min(window, PBASE[slots - 1] + (1 << PEXTRA[slots - 1]))
|
||||
head, prev = {}, {}
|
||||
frames = []
|
||||
p = 0
|
||||
|
||||
def insert(q):
|
||||
if q + 3 <= len(data):
|
||||
k = data[q:q + 3]
|
||||
prev[q] = head.get(k)
|
||||
head[k] = q
|
||||
while p < len(data):
|
||||
end = min(len(data), p + FRAME)
|
||||
enc = Encoder()
|
||||
while p < end:
|
||||
limit = min(259, end - p)
|
||||
best, boff = 0, 0
|
||||
if limit >= 3:
|
||||
q = head.get(data[p:p + 3])
|
||||
chain = 0
|
||||
while q is not None and chain < maxchain and p - q <= limw:
|
||||
l = 0
|
||||
while l < limit and data[q + l] == data[p + l]:
|
||||
l += 1
|
||||
o = p - q
|
||||
ok = l >= 5 or (l == 4 and o <= lim4) or (l == 3 and o <= lim3)
|
||||
if ok and l > best:
|
||||
best, boff = l, o
|
||||
q = prev.get(q)
|
||||
chain += 1
|
||||
if best >= 3:
|
||||
o1 = boff - 1
|
||||
s = slot_of(o1)
|
||||
if best == 3:
|
||||
enc.encode(sel, 4)
|
||||
enc.encode(m3, s)
|
||||
elif best == 4:
|
||||
enc.encode(sel, 5)
|
||||
enc.encode(m4, s)
|
||||
else:
|
||||
l5 = best - 5
|
||||
ls = max(i for i in range(27) if LBASE[i] <= l5)
|
||||
enc.encode(sel, 6)
|
||||
enc.encode(mlen, ls)
|
||||
enc.raw(l5 - LBASE[ls], LEXTRA[ls])
|
||||
enc.encode(m5, s)
|
||||
enc.raw(o1 - PBASE[s], PEXTRA[s])
|
||||
for k in range(best):
|
||||
insert(p + k)
|
||||
p += best
|
||||
else:
|
||||
b = data[p]
|
||||
enc.encode(sel, b >> 6)
|
||||
enc.encode(lit[b >> 6], b)
|
||||
insert(p)
|
||||
p += 1
|
||||
frames.append(enc.finish())
|
||||
return frames
|
||||
@@ -0,0 +1,247 @@
|
||||
# Cabinet fixtures (tools/fixtures.py): cabinets by gcab (stored and MSZIP folders, paths), lcab (stored), our own
|
||||
# minimal cabinet builder below (MSZIP blocks deflated with the previous block as the zlib dictionary, several
|
||||
# folders, reserve areas, attributes, UTF-8 names; LZX and Quantum folders from the fixture compressors _lzx.py /
|
||||
# _quantum.py, since no packaged tool writes them), the libmspack test cabinets read from the nix store (test data,
|
||||
# not committed: normal / reserve / multi-part / mszip_lzx_qtm samples and the broken ones), and our writer's output.
|
||||
# The reference data is what cabextract extracts and lists (sizes, data CRCs, the DOS times as UTC); every fixture
|
||||
# LZX / Quantum cabinet must extract with cabextract to the original bytes, and cabextract, gcab and 7z must extract
|
||||
# our writer's cabinets to the same bytes.
|
||||
# tests/gen/cab.luau { cases = { { name, data, entries = { { name, size, crc, mtime } } } }, ours = { ok, log },
|
||||
# spanned = { { name, data } }, bad = { { name, data } } }
|
||||
import calendar, importlib.util, os, re, struct, subprocess, time, zlib
|
||||
|
||||
_s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py"))
|
||||
A = importlib.util.module_from_spec(_s)
|
||||
_s.loader.exec_module(A)
|
||||
_s = importlib.util.spec_from_file_location("_lzx", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_lzx.py"))
|
||||
L = importlib.util.module_from_spec(_s)
|
||||
_s.loader.exec_module(L)
|
||||
_s = importlib.util.spec_from_file_location("_quantum", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_quantum.py"))
|
||||
Q = importlib.util.module_from_spec(_s)
|
||||
_s.loader.exec_module(Q)
|
||||
|
||||
INPUTS = ["tools/fixtures/_arch2.py", "tools/fixtures/_lzx.py", "tools/fixtures/_quantum.py"]
|
||||
ENV = dict(os.environ, TZ="UTC")
|
||||
|
||||
|
||||
def checksum(data, seed=0):
|
||||
"""the CFDATA checksum ([MS-CAB] 2.4)"""
|
||||
s = seed
|
||||
n = len(data) - len(data) % 4
|
||||
for i in range(0, n, 4):
|
||||
s ^= struct.unpack_from("<I", data, i)[0]
|
||||
t = 0
|
||||
for b in data[n:]:
|
||||
t = (t << 8) | b
|
||||
return s ^ t
|
||||
|
||||
|
||||
def dos(t):
|
||||
y, mo, d, h, mi, s = time.gmtime(t)[:6]
|
||||
return ((y - 1980) << 9) | (mo << 5) | d, (h << 11) | (mi << 5) | (s // 2)
|
||||
|
||||
|
||||
def build(folders, reserve=None):
|
||||
"""a cabinet: folders = [(typeCompress, [(name, bytes, attribs, mtime)], encode(stream) -> [(payload, size)])];
|
||||
reserve = (header bytes, folder size, data size)"""
|
||||
hres, fres, dres = reserve or (b"", 0, 0)
|
||||
flags = 4 if reserve else 0
|
||||
head = 36 + (4 + len(hres) if reserve else 0)
|
||||
nfiles = sum(len(f[1]) for f in folders)
|
||||
files = b""
|
||||
blocks = []
|
||||
for fi, (typ, fl, enc) in enumerate(folders):
|
||||
off = 0
|
||||
stream = b""
|
||||
for name, data, attr, mt in fl:
|
||||
d, t = dos(mt)
|
||||
files += struct.pack("<IIHHHH", len(data), off, fi, d, t, attr) + name + b"\0"
|
||||
off += len(data)
|
||||
stream += data
|
||||
blocks.append(enc(stream))
|
||||
coff = head + len(folders) * (8 + fres)
|
||||
dat = coff + len(files)
|
||||
folder_tab = b""
|
||||
data = b""
|
||||
for (typ, _, _), bl in zip(folders, blocks):
|
||||
folder_tab += struct.pack("<IHH", dat + len(data), len(bl), typ) + b"\0" * fres
|
||||
for payload, n in bl:
|
||||
csum = checksum(struct.pack("<HH", len(payload), n), checksum(payload))
|
||||
data += struct.pack("<IHH", csum, len(payload), n) + b"\x5a" * dres + payload
|
||||
total = coff + len(files) + len(data)
|
||||
hdr = b"MSCF" + struct.pack("<IIIIIBBHHHHH", 0, total, 0, coff, 0, 3, 1, len(folders), nfiles, flags, 0x1234, 0)
|
||||
if reserve:
|
||||
hdr += struct.pack("<HBB", len(hres), fres, dres) + hres
|
||||
return hdr + folder_tab + files + data
|
||||
|
||||
|
||||
def chunks(stream):
|
||||
return [stream[s:s + 32768] for s in range(0, len(stream), 32768)]
|
||||
|
||||
|
||||
def store(stream):
|
||||
return [(c, len(c)) for c in chunks(stream)]
|
||||
|
||||
|
||||
def mszip_dict(stream):
|
||||
out, prev = [], b""
|
||||
for chunk in chunks(stream):
|
||||
c = zlib.compressobj(9, zlib.DEFLATED, -15, zdict=prev) if prev else zlib.compressobj(9, zlib.DEFLATED, -15)
|
||||
out.append((b"CK" + c.compress(chunk) + c.flush(), len(chunk)))
|
||||
prev = chunk
|
||||
return out
|
||||
|
||||
|
||||
def lzx(wbits, e8size=0, seed=1, plan=None):
|
||||
def enc(stream):
|
||||
data, frames = L.compress(stream, wbits, e8size, seed, plan)
|
||||
out, p = [], 0
|
||||
for i, n in enumerate(frames):
|
||||
out.append((data[p:p + n], min(32768, len(stream) - i * 32768)))
|
||||
p += n
|
||||
assert p == len(data)
|
||||
return out
|
||||
return enc
|
||||
|
||||
|
||||
def quantum(wbits):
|
||||
def enc(stream):
|
||||
frames = Q.compress(stream, wbits)
|
||||
return [(f, min(32768, len(stream) - i * 32768)) for i, f in enumerate(frames)]
|
||||
return enc
|
||||
|
||||
|
||||
LIST = re.compile(r"^\s*(\d+) \| (\d\d)\.(\d\d)\.(\d{4}) (\d\d):(\d\d):(\d\d) \| (.*)$")
|
||||
|
||||
|
||||
def reference(path, tmp, tag):
|
||||
"""cabextract's listing (name -> mtime) and extraction (name -> size, crc)"""
|
||||
listing = A.tool(["cabextract"], ["cabextract", "-l", path]).decode("utf-8", "replace")
|
||||
times = {}
|
||||
for line in listing.splitlines():
|
||||
m = LIST.match(line)
|
||||
if m:
|
||||
d, mo, y, h, mi, s = (int(x) for x in m.group(2, 3, 4, 5, 6, 7))
|
||||
times[m.group(8).replace("\\", "/")] = calendar.timegm((y, mo, d, h, mi, s))
|
||||
out = os.path.join(tmp, "x-" + tag)
|
||||
os.makedirs(out)
|
||||
subprocess.run(["nix", "shell", "nixpkgs#cabextract", "-c", "cabextract", "-q", "-d", out, path], check=True,
|
||||
capture_output=True, env=ENV)
|
||||
ents = []
|
||||
for n, c in sorted(A.read_tree(out).items()):
|
||||
e = {"name": n, "size": os.path.getsize(os.path.join(out, n)), "crc": c}
|
||||
if n in times:
|
||||
e["mtime"] = times[n]
|
||||
ents.append(e)
|
||||
return ents
|
||||
|
||||
|
||||
def mspack_cabs():
|
||||
"""the libmspack source's test cabinets (nix store path of its tarball, unpacked into a temporary directory)"""
|
||||
src = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#libmspack.src"], check=True,
|
||||
capture_output=True).stdout.decode().strip()
|
||||
return src
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(47)
|
||||
tmp = A.tmpdir()
|
||||
try:
|
||||
work = os.path.join(tmp, "w")
|
||||
text = b"the quick brown fox jumps over the lazy dog\n" * 3000
|
||||
rand = rng.randbytes(70000)
|
||||
A.tree(A.FILES + [("dir/sub/text.txt", text), ("dir/rand.bin", rand),
|
||||
("dir/runs.bin", b"\0" * 50000 + b"\xff" * 30000)], work)
|
||||
names = [n for n, _ in A.FILES] + ["dir/sub/text.txt", "dir/rand.bin", "dir/runs.bin"]
|
||||
cases = []
|
||||
|
||||
def add(name, path):
|
||||
cases.append({"name": name, "data": open(path, "rb").read(), "entries": reference(path, tmp, str(len(cases)))})
|
||||
|
||||
for z in ("", "-z"):
|
||||
arc = os.path.join(tmp, "gcab%s.cab" % z)
|
||||
A.tool(["gcab"], ["gcab", "-c"] + ([z] if z else []) + [arc] + names, cwd=work)
|
||||
add("gcab " + (z or "store"), arc)
|
||||
arc = os.path.join(tmp, "lcab.cab")
|
||||
A.tool(["lcab"], ["lcab", "-r", "dir", "hello.txt", arc], cwd=work)
|
||||
add("lcab", arc)
|
||||
# our builder: MSZIP with the dictionary, two folders (stored + MSZIP), reserve areas, attributes, UTF-8
|
||||
big = text + rand[:20000] + text[:50000]
|
||||
cab1 = build([(1, [(b"a\\text.txt", big, 0x20, 1700000000), (b"b.bin", rand, 0x01, 1600000000)], mszip_dict)])
|
||||
cab2 = build([(0, [(b"stored.txt", b"stored data " * 5000, 0x20, 1700000000)], store),
|
||||
(1, [("naïve ☃.txt".encode(), text, 0x80 | 0x20, 1700000002), (b"empty", b"", 0x20, 1700000000)], mszip_dict)],
|
||||
reserve=(b"HEADER-RESERVE", 6, 3))
|
||||
for i, c in enumerate((cab1, cab2)):
|
||||
p = os.path.join(tmp, "built%d.cab" % i)
|
||||
open(p, "wb").write(c)
|
||||
A.tool(["cabextract"], ["cabextract", "-t", p]) # checksums and data as cabextract reads them
|
||||
add(("mszip with dictionary", "two folders, reserve, utf-8")[i], p)
|
||||
# LZX (our fixture compressor, checked by cabextract): windows 2^15 .. 2^21, the three block types, E8
|
||||
x86 = bytearray(rng.randbytes(90000))
|
||||
for i in range(0, len(x86) - 5, 23):
|
||||
x86[i] = 0xE8
|
||||
x86 = bytes(x86) + text[:40000]
|
||||
lzx_cases = [
|
||||
("lzx 2^15 text", 15, 0, [(b"t.txt", text[:100000])], None),
|
||||
("lzx 2^16 mixed", 16, 0, [(b"a.txt", text), (b"b.bin", rand[:30000]), (b"c.txt", text[:5000])], None),
|
||||
("lzx 2^17 types", 17, 0, [(b"m.bin", big)], [(1, 40000), (2, 30001), (3, 7777), (2, 50000), (3, 4), (1, len(big) - 127782)]),
|
||||
("lzx 2^21 e8", 21, 12000000, [(b"x86.exe", x86), (b"tail.txt", text[:3000])], None),
|
||||
("lzx 2^18 e8 small", 18, 70000, [(b"s.bin", x86[:20000])], [(2, 20000)]),
|
||||
]
|
||||
for i, (label, wb, e8size, fl, plan) in enumerate(lzx_cases):
|
||||
c = build([(3 | (wb << 8), [(n, d, 0x20, 1700000000) for n, d in fl], lzx(wb, e8size, 100 + i, plan))])
|
||||
p = os.path.join(tmp, "lzx%d.cab" % i)
|
||||
open(p, "wb").write(c)
|
||||
ents = reference(p, tmp, "lzx%d" % i)
|
||||
want = {n.decode(): zlib.crc32(d) for n, d in fl}
|
||||
if {e["name"]: e["crc"] for e in ents} != want:
|
||||
raise RuntimeError("cabextract does not extract the fixture LZX cabinet " + label)
|
||||
cases.append({"name": label, "data": c, "entries": ents})
|
||||
# Quantum (our fixture compressor, checked by cabextract): windows 2^10 .. 2^21, model rescaling and re-sorting
|
||||
quantum_cases = [
|
||||
("quantum 2^10 text", 10, [(b"q.txt", text[:20000])]),
|
||||
("quantum 2^16 mixed", 16, [(b"a.txt", text[:60000]), (b"b.bin", rand[:20000]), (b"c.bin", x86[:30000])]),
|
||||
("quantum 2^21 big", 21, [(b"big.bin", big)]),
|
||||
]
|
||||
for i, (label, wb, fl) in enumerate(quantum_cases):
|
||||
c = build([(2 | (4 << 4) | (wb << 8), [(n, d, 0x20, 1700000000) for n, d in fl], quantum(wb))])
|
||||
p = os.path.join(tmp, "qtm%d.cab" % i)
|
||||
open(p, "wb").write(c)
|
||||
ents = reference(p, tmp, "qtm%d" % i)
|
||||
want = {n.decode(): zlib.crc32(d) for n, d in fl}
|
||||
if {e["name"]: e["crc"] for e in ents} != want:
|
||||
raise RuntimeError("cabextract does not extract the fixture Quantum cabinet " + label)
|
||||
cases.append({"name": label, "data": c, "entries": ents})
|
||||
# the libmspack test cabinets
|
||||
ms = os.path.join(tmp, "ms")
|
||||
os.makedirs(ms)
|
||||
subprocess.run(["tar", "xzf", mspack_cabs(), "-C", ms, "--wildcards", "*/test/test_files/cabd/*.cab"], check=True)
|
||||
cabd = os.path.join(ms, os.listdir(ms)[0], "test", "test_files", "cabd")
|
||||
for n in ("normal_2files_1folder", "normal_2files_2folders", "normal_255c_filename", "reserve_---", "reserve_--D",
|
||||
"reserve_-F-", "reserve_-FD", "reserve_H--", "reserve_H-D", "reserve_HF-", "reserve_HFD", "mszip_lzx_qtm"):
|
||||
add("libmspack " + n, os.path.join(cabd, n + ".cab"))
|
||||
spanned = [{"name": n, "data": open(os.path.join(cabd, n + ".cab"), "rb").read()}
|
||||
for n in ("multi_basic_pt1", "multi_basic_pt2", "multi_basic_pt3")]
|
||||
# broken cabinets cabextract fails on (crafted bad trees, loops, short headers / strings)
|
||||
bad = [{"name": n, "data": open(os.path.join(cabd, n), "rb").read()} for n in sorted(os.listdir(cabd))
|
||||
if n.endswith(".cab") and (n.startswith(("partial_", "bad_", "lzx-")) or (n.startswith("cve-") and "9732" not in n))]
|
||||
# our writer, extracted by the reference tools
|
||||
log, ok = [], True
|
||||
for opts in ("compression=mszip", "compression=none", "compression=mszip,level=1"):
|
||||
data = A.ours(ctx, "cab", opts)
|
||||
p = os.path.join(tmp, "ours.cab")
|
||||
open(p, "wb").write(data)
|
||||
for tool, argv in (("cabextract", ["cabextract", "-q", "-d", "{o}", p]), ("gcab", ["gcab", "-x", "-C", "{o}", p]),
|
||||
("p7zip", ["7z", "x", "-o{o}", p])):
|
||||
out = os.path.join(tmp, "o-%s-%d" % (tool, len(log)))
|
||||
os.makedirs(out)
|
||||
r = subprocess.run(["nix", "shell", "nixpkgs#" + tool, "-c"] + [a.replace("{o}", out) for a in argv],
|
||||
capture_output=True, env=ENV)
|
||||
got = A.read_tree(out)
|
||||
want = {n: zlib.crc32(d) for n, d in A.FILES}
|
||||
good = r.returncode == 0 and got == want
|
||||
ok = ok and good
|
||||
log.append("%s %s: %s" % (opts, tool, "ok" if good else "FAILED %r" % (got,)))
|
||||
ctx.emit("cab", {"cases": cases, "ours": {"ok": ok, "log": "; ".join(log)}, "spanned": spanned, "bad": bad})
|
||||
finally:
|
||||
A.rmtree(tmp)
|
||||
@@ -0,0 +1,30 @@
|
||||
# Docs inputs for the archive page's Cabinet section (tools/fixtures.py; tools/docs_check.py explains the inputs): an
|
||||
# MSZIP cabinet of a small tree by gcab.
|
||||
# tests/gen/docs_arch_cab.luau { files = { [name] = bytes }, vars = { cabBytes = "setup.cab" } }
|
||||
import importlib.util, os, subprocess, tempfile
|
||||
|
||||
INPUTS = ["tools/docs_check.py"]
|
||||
|
||||
MTIME = 1767225600 # 2026-01-01T00:00:00Z
|
||||
|
||||
|
||||
def docs_check(ctx):
|
||||
spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
dc = docs_check(ctx)
|
||||
files = {}
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
os.makedirs(os.path.join(d, "bin"))
|
||||
for n, data in (("readme.txt", b"formats-luau cabinet\n" * 20), ("bin/tool.dll", bytes(range(256)) * 64)):
|
||||
with open(os.path.join(d, n), "wb") as f:
|
||||
f.write(data)
|
||||
os.utime(os.path.join(d, n), (MTIME, MTIME))
|
||||
subprocess.run(["nix", "shell", "nixpkgs#gcab", "-c", "gcab", "-c", "-z", "setup.cab", "readme.txt", "bin/tool.dll"],
|
||||
cwd=d, check=True, capture_output=True, env=dict(os.environ, TZ="UTC"))
|
||||
files["setup.cab"] = open(os.path.join(d, "setup.cab"), "rb").read()
|
||||
dc.emit_inputs(ctx, files, {"cabBytes": "setup.cab"})
|
||||
Reference in new issue
Block a user