Skip to content
Open
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
3 changes: 3 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## 2024-06-24 - [yEnc decoding optimization]
**Learning:** Python's manual byte-by-byte iteration is slow for yEnc decoding. We can shift the workload to C-backed functions by using `bytes.translate` to decode non-escaped segments, and `bytes.find` to quickly locate the escape character (`=`). When escaping, `(char - 64 - 42) % 256` simplifies algebraically to `(char - 106) % 256`. Also, trailing escapes at line boundaries need to be correctly identified by checking length.
**Action:** Always prefer C-backed built-in methods like `translate()` and `find()` over manual loops when processing raw byte strings in Python.
28 changes: 18 additions & 10 deletions verify_nzb.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,19 +115,27 @@ def _parse_yenc_attrs(line: bytes) -> dict[str, str]:
return attrs


_YENC_DECODE_MAP = bytes((i - 42) % 256 for i in range(256))

def _decode_yenc_lines(lines: Iterable[bytes]) -> bytes:
decoded = bytearray()
for line in lines:
index = 0
while index < len(line):
byte = line[index]
if byte == 61:
index += 1
if index >= len(line):
raise ValueError("dangling yEnc escape")
byte = (line[index] - 64) % 256
decoded.append((byte - 42) % 256)
index += 1
pos = 0
line_len = len(line)
while True:
escape_pos = line.find(b"=", pos)
if escape_pos == -1:
decoded.extend(line[pos:].translate(_YENC_DECODE_MAP))
break

decoded.extend(line[pos:escape_pos].translate(_YENC_DECODE_MAP))

if escape_pos + 1 >= line_len:
raise ValueError("dangling yEnc escape")

decoded.append((line[escape_pos + 1] - 106) % 256)
pos = escape_pos + 2

return bytes(decoded)


Expand Down