# 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("= 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("= 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