mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 22:58:37 +00:00
Nine archive scanners sliced every gap out of the mmap to test whether it was all zero (`gap = m[last:s]; gap.count(0) == len(gap)`). The slice is a copy, so a gap of N bytes allocated N bytes at once; about half of story000.rpf (~20 GB) is non-zlib, which ends in MemoryError on a 16 GB machine. tools/zero_span.py compares the gap with zeros 4 MiB at a time and stops at the first non-zero window, with the same counts (all of a gap is padding when every byte is zero, otherwise all of it is unread). rpf9_carve, rpf9_names, bvh_index, navmesh_index, navmesh_decode, rbf0_index, anim_index, restofworld_index and story_index use it. tests/test_zero_span.py checks the counts against the old expression and runs each scanner on a 48 MiB gap under tracemalloc: 50-51 MiB heap peak on main, under 24 MiB with this change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
34 lines
1.5 KiB
Python
34 lines
1.5 KiB
Python
"""Classify the bytes between two carved streams without copying them.
|
|
|
|
The archive scanners count the bytes they could not read as either zero padding or unread data: a gap counts as
|
|
padding only when every byte in it is zero. Slicing an mmap copies the slice, so `gap = m[last:s]` allocates the
|
|
whole gap at once. On a large archive a gap can run to gigabytes (story000.rpf, about 20 GB, cannot be indexed on
|
|
a 16 GB machine that way), so the gap is compared against zeros one window at a time instead, and the first
|
|
non-zero window ends the check.
|
|
"""
|
|
|
|
WINDOW = 1 << 22 # 4 MiB: the most a check allocates, besides the shared zero block
|
|
_ZEROS = bytes(WINDOW)
|
|
|
|
|
|
def all_zero(buf, start: int, end: int) -> bool:
|
|
"""True when buf[start:end] is empty or all zero bytes. Reads at most WINDOW bytes at a time."""
|
|
end = min(end, len(buf))
|
|
p = start
|
|
while p < end:
|
|
q = min(end, p + WINDOW)
|
|
if buf[p:q] != _ZEROS[:q - p]:
|
|
return False
|
|
p = q
|
|
return True
|
|
|
|
|
|
def gap_split(buf, start: int, end: int) -> tuple[int, int]:
|
|
"""(zero_padding, unread) bytes for the gap buf[start:end], counted as the scanners always have: all of
|
|
it is padding when every byte is zero, otherwise all of it is unread. The range is clipped to the buffer
|
|
the way a slice is, so the counts match len(buf[start:end])."""
|
|
end = min(end, len(buf))
|
|
start = min(start, end)
|
|
n = end - start
|
|
return (n, 0) if all_zero(buf, start, end) else (0, n)
|