Update 2 files

- /_data/other_repo_list.csv
- /_posts/2026-11-01-compress.md
This commit is contained in:
mayx committed 2026-12-06 13:56:41 +00:00
1 parent dca1399b2b
commit d039c9a3b7
2 files changed
+165 -42

No files matched your search

+165 -25
View File
@@ -768,7 +768,7 @@ Show Code
```python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Pack files/directories plus an exact copy of this ZIP archive.
"""Pack files/directories plus an exact copy of this ZIP archive, compressed.
Example: python zip_quine.py ./site ./site.zip
One directory packs its contents; multiple inputs retain their basenames.
@@ -1023,6 +1023,153 @@ def _large_plan(e):
return best
# ------------------------------------------------- real compression layer
LEVEL = 9
WINDOW = 32768
BIG = max(CONNECTORS) # (65436, 25, 120): fewest cells per file
def _dz(data, a, b, final):
"""Raw Deflate of data[a:b], primed with the 32 KiB that precede a.
Non-final output ends on a byte boundary (sync flush), so a connector can
follow it. The decoder window is the real output, so the dictionary is
simply the raw bytes before a, regardless of how they were encoded."""
kw = {'zdict': bytes(data[max(0, a - WINDOW):a])} if a else {}
c = zlib.compressobj(LEVEL, zlib.DEFLATED, -15, 9,
zlib.Z_DEFAULT_STRATEGY, **kw)
return (c.compress(data[a:b])
+ c.flush(zlib.Z_FINISH if final else zlib.Z_SYNC_FLUSH))
def _fit_cell(data, end, cap, final, rho):
"""Pick (start, a2, z): data[start:a2] stored raw plus z = Deflate of
data[a2:end] fill exactly cap bytes, covering data[start:end].
The stored part is written through the cell's own stored-block header, so
it costs no extra bytes. Coverage is maximal when a2 is the smallest start
whose compressed size still fits."""
cache = {}
def Z(a):
if a not in cache:
cache[a] = _dz(data, a, end, final)
return cache[a]
def ok(a):
return len(Z(a)) <= cap
if end <= 0 or not ok(end):
return None
if ok(0):
a2 = 0
else:
a = max(0, end - int(cap / max(rho, 1e-3)))
for _ in range(6):
z = len(Z(a))
if z == cap:
break
new = min(max(end - int((end - a) * cap / z), 0), end)
if new == a:
break
a = new
step = 256
if ok(a):
good, bad = a, max(0, a - step)
while ok(bad):
good, step = bad, step * 4
bad = max(0, bad - step)
else:
bad, good = a, min(end, a + step)
while not ok(good):
bad, step = good, step * 4
good = min(end, good + step)
while good - bad > 1:
mid = (good + bad) // 2
if ok(mid):
good = mid
else:
bad = mid
a2 = good
for a2c in range(a2, min(end, a2 + 1024) + 1):
z = Z(a2c)
r = cap - len(z)
if r >= 0 and a2c - r >= 0:
return a2c - r, a2c, z
return None
def _big_cells_compressed(e):
"""Cells for one member whose Deflate stream spans several cells.
Cell 0 has a free length, so it takes whatever the right-to-left packing
leaves over. Every later cell has the table length and is exactly full."""
data, n, N = e['data'], len(e['encoded']), len(e['data'])
lc, m, c1 = BIG
g = geometry(lc, m, c1)
ph, k = g['p_head'], g['k']
rho = len(_dz(data, 0, N, True)) / max(N, 1)
rev, end = [], N
while True:
final = not rev
z0 = _dz(data, 0, end, final) if end else b''
if 30 + n + len(z0) + (8 if final else k) <= 65535:
break
cap = lc - ph - (8 if final else k)
sol = _fit_cell(data, end, cap, final, rho)
if sol is None:
raise ValueError('no exact fit for ' + e['name'])
if not 0 <= sol[0] < end:
raise ValueError('cell made no progress for ' + e['name'])
rev.append(sol + (final,))
end = sol[0]
if len(rev) > 4096:
raise ValueError('too many cells for ' + e['name'])
rev.reverse()
tail = connector_tail(g['unit'], g['m'])
csize = len(z0) + (k + 8 if rev else 0)
for start, a2, z, final in rev:
csize += ph + (a2 - start) + len(z) + (0 if final else k + 8)
e['method'], e['csize'] = 8, csize
cells = [bytearray(_local(e) + z0 + (tail if rev else bytes(8)))]
for start, a2, z, final in rev:
r = a2 - start
cell = (g['head'] + struct.pack('<HH', r, r ^ 65535)
+ data[start:a2] + z + (bytes(8) if final else tail))
if len(cell) != lc:
raise RuntimeError('compressed cell length mismatch')
cells.append(bytearray(cell))
return cells
def _big_cells_stored(e, base_index):
"""Original layout: Deflate stored blocks only (no compression)."""
cells = []
g = _large_plan(e)
e.update(method=8, csize=g['csize'], cell_index=base_index, cell_relative=0)
tail, at = connector_tail(g['unit'], g['m']), g['first']
cell = (_local(e, extra=_extra_padding(g['extra']))
+ b'\0' + struct.pack('<HH', at, at ^ 65535)
+ e['data'][:at] + tail)
if len(cell) != g['lc']:
raise RuntimeError('first payload cell length mismatch')
cells.append(bytearray(cell))
for index in range(1, g['count']):
last = index == g['count'] - 1
size = g['last'] if last else g['middle']
cell = ((g['head_final'] if last else g['head'])
+ struct.pack('<HH', size, size ^ 65535)
+ e['data'][at:at + size])
at += size
cell += bytes(g['lc'] - len(cell)) if last else tail
if len(cell) != g['lc']:
raise RuntimeError('payload cell length mismatch')
cells.append(bytearray(cell))
if at != e['size']:
raise RuntimeError('payload split length mismatch')
return cells
def _solve_patch(baseline):
# The final four bytes are a unique free field in the archive comment.
# CRC differences do not depend on the prefix bytes, so this needs only
@@ -1084,36 +1231,27 @@ def build(entries, self_name, *, mtime=0):
pending, pending_entries = bytearray(), []
for e in items:
record_size = 30 + len(e['encoded']) + len(e['data'])
stream = e['data']
if stream:
z = _dz(stream, 0, len(stream), True)
if len(z) < len(stream):
e['method'], e['csize'], stream = 8, len(z), z
record_size = 30 + len(e['encoded']) + len(stream)
if record_size <= 65527:
if len(pending) + record_size > 65527:
flush_small()
pending_entries.append((e, len(pending)))
pending += _local(e) + e['data']
pending += _local(e) + stream
continue
flush_small()
g = _large_plan(e)
e.update(method=8, csize=g['csize'], cell_index=len(cells), cell_relative=0)
tail, at = connector_tail(g['unit'], g['m']), g['first']
cell = (_local(e, extra=_extra_padding(g['extra']))
+ b'\0' + struct.pack('<HH', at, at ^ 65535)
+ e['data'][:at] + tail)
if len(cell) != g['lc']:
raise RuntimeError('first payload cell length mismatch')
cells.append(bytearray(cell))
for index in range(1, g['count']):
last = index == g['count'] - 1
size = g['last'] if last else g['middle']
cell = ((g['head_final'] if last else g['head'])
+ struct.pack('<HH', size, size ^ 65535)
+ e['data'][at:at + size])
at += size
cell += bytes(g['lc'] - len(cell)) if last else tail
if len(cell) != g['lc']:
raise RuntimeError('payload cell length mismatch')
cells.append(bytearray(cell))
if at != e['size']:
raise RuntimeError('payload split length mismatch')
e['cell_index'], e['cell_relative'] = len(cells), 0
try:
if e['method'] != 8 or len(stream) > 0.98 * len(e['data']):
raise ValueError('incompressible')
cells.extend(_big_cells_compressed(e))
except ValueError:
e['method'], e['csize'] = 0, e['size']
cells.extend(_big_cells_stored(e, len(cells)))
flush_small()
offsets, position = [], prefix_size
for cell in cells:
@@ -1421,6 +1559,8 @@ if __name__ == '__main__':
```
</details>
(2026.12.06更新)最近几天有幸用到了Claude Fable 5.1,顺便让它看了看我的几个压缩包,想不到它说这个ZIP Quine居然还能做到压缩,而且不像7z Quine那样是双层压缩,这大概也是重叠布局的优势吧……所以顺手把能压缩的新代码贴上来了。
## 更多格式——RAR Quine
其实大多数常用的压缩算法都和ZIP差不多,核心思想基本上都是LZ77那套用距离和长度来表示重复内容,然后再用各种熵编码来尽可能用少的比特存储数据……所以说RAR Quine理论上也可以存在,毕竟原理都差不多。同样,我也试着让AI做了一下,依旧轻轻松松就做出来了。不过毕竟RAR不是开源软件,生成的代码我就不放出来了,这里有一份生成后的RAR Quine:[quine.rar](/assets/quine.rar),如果有人有兴趣,也可以研究一下这个档案。