Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 21 additions & 7 deletions src/sillybos/pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,6 @@ def _any_name(*names: str) -> re.Pattern[bytes]:
("ccitt", _any_name("CCITTFaxDecode", "CCF")),
)
_SCAN_CHUNK = 1024 * 1024
_SCAN_OVERLAP = 32 # longer than the longest escaped spelling of the name


class PdfInfoMissing(RuntimeError):
Expand Down Expand Up @@ -180,21 +179,36 @@ def _tool(tool: str, args: list[str], path: Path, timeout: float) -> str:
def _names_in(path: Path, *patterns: re.Pattern[bytes]) -> list[bool]:
"""Whether the bytes of the file spell each name anywhere, one answer per pattern.

Read a chunk at a time with a short overlap, so a name across a chunk
boundary is still seen and the memory used does not grow with the file.
Read a chunk at a time, so the memory used does not grow with the file,
and carry the end of each chunk over to the next, so a name across a
chunk boundary is still seen. What is carried is as long as the longest
pattern, and a pattern made by `_name_pattern` is longer than any
spelling it matches: a fixed 32 bytes was shorter
than `/JBIG2Decode` or `/CCITTFaxDecode` with every letter escaped, so
one placed just before a boundary went unseen.

A name that ends exactly where a chunk does is not counted yet, since
the letters that follow may make it another name (`/Launch` and then
`er`); the next chunk settles it. One that ends where the file does is
counted.
"""
overlap = max(len(pattern.pattern) for pattern in patterns)
found = [False] * len(patterns)
at_end = [False] * len(patterns)
tail = b""
with path.open("rb") as f:
while chunk := f.read(_SCAN_CHUNK):
window = tail + chunk
for i, pattern in enumerate(patterns):
if not found[i] and pattern.search(window):
found[i] = True
if found[i]:
continue
match = pattern.search(window)
found[i] = match is not None and match.end() < len(window)
at_end[i] = match is not None and match.end() == len(window)
if all(found):
break
tail = chunk[-_SCAN_OVERLAP:]
return found
tail = window[-overlap:]
return [hit or last for hit, last in zip(found, at_end, strict=True)]


def _has_launch_action(path: Path) -> bool:
Expand Down
66 changes: 66 additions & 0 deletions tests/test_pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@
from sillybos.pdf import PdfInfoMissing
from tests import corpus

_CODEC_FILTERS = (
("DCTDecode", "jpeg"),
("JPXDecode", "jpx"),
("JBIG2Decode", "jbig2"),
("CCITTFaxDecode", "ccitt"),
)
needs_pdfinfo = pytest.mark.skipif(shutil.which("pdfinfo") is None, reason="pdfinfo (poppler)")


Expand Down Expand Up @@ -127,6 +133,66 @@ def test_the_launch_scan_sees_a_name_across_a_chunk_boundary(
assert pdf_module._has_launch_action(path)


def _escaped(name: str) -> bytes:
"""The PDF name with every letter written as a `#xx` escape, its longest spelling."""
return b"/" + b"".join(b"#%02x" % ord(c) for c in name)


@pytest.mark.parametrize(
("name", "pattern"),
[
("Launch", pdf_module._LAUNCH),
("JavaScript", pdf_module._JAVASCRIPT_NAME),
("Rendition", pdf_module._RENDITION),
*((name, dict(pdf_module._CODEC_NAMES)[codec]) for name, codec in _CODEC_FILTERS),
],
)
def test_the_scan_sees_the_longest_spelling_wherever_a_chunk_boundary_falls(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, name: str, pattern: re.Pattern[bytes]
) -> None:
"""`/JBIG2Decode` fully escaped is 34 bytes; the scan once carried 32 across a boundary."""
chunk = 64
monkeypatch.setattr(pdf_module, "_SCAN_CHUNK", chunk)
path = tmp_path / "a.pdf"
for spelling in (b"/" + name.encode(), _escaped(name)):
for start in range(chunk - len(spelling) - 2, chunk + 2):
path.write_bytes(b" " * start + spelling + b" >>" + b" " * chunk)
assert pdf_module._names_in(path, pattern) == [True], (spelling, start)
# ...and the last bytes of the file are a name too.
path.write_bytes(b" " * start + spelling)
assert pdf_module._names_in(path, pattern) == [True], (spelling, start)


def test_the_scan_sees_a_name_longer_than_a_chunk(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(pdf_module, "_SCAN_CHUNK", 16)
path = tmp_path / "a.pdf"
path.write_bytes(b"%PDF-1.4\n<< /Filter " + _escaped("CCITTFaxDecode") + b" >>")
assert pdf_module._names_in(path, dict(pdf_module._CODEC_NAMES)["ccitt"]) == [True]


def test_the_scan_answers_for_each_name_wherever_in_the_file_it_is(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(pdf_module, "_SCAN_CHUNK", 16)
path = tmp_path / "a.pdf"
path.write_bytes(b"/Launch " + b" " * 40 + b"/Rendition " + b" " * 40)
names = (pdf_module._LAUNCH, pdf_module._JAVASCRIPT_NAME, pdf_module._RENDITION)
assert pdf_module._names_in(path, *names) == [True, False, True]


@pytest.mark.parametrize("after", [b"er /F (x) >>", b"2", b"#65r"])
def test_a_name_cut_by_a_chunk_boundary_is_read_whole(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, after: bytes
) -> None:
"""`/Launch` at the end of one chunk and `er` at the start of the next is `/Launcher`."""
monkeypatch.setattr(pdf_module, "_SCAN_CHUNK", 16)
path = tmp_path / "a.pdf"
path.write_bytes(b"%PDF-1.4\n/Launch" + after) # "/Launch" ends at byte 16
assert not pdf_module._has_launch_action(path)


@pytest.mark.parametrize(
("body", "scripted"),
[
Expand Down
Loading