4: исправление по ревью — проверка смысла чанков PNG (палитра, tRNS, порядок, текст), регрессионные тесты, evidence

This commit is contained in:
kalibr456
2026-10-22 14:30:53 +03:00
parent 5c3a31db2e
commit 4d4b914676
26 changed files with 587 additions and 279 deletions
+22 -3
View File
@@ -22,7 +22,7 @@ def chunk(kind: bytes, data: bytes) -> bytes:
def png(width, height, *, gray=False, noise=False, interlace=0, pad_to=None, idat=None) -> bytes:
"""PNG width x height. noise=True — случайные пиксели (почти не сжимаются, файл большой).
pad_to — дополнить файл служебным чанком prVt до точного размера в байтах.
pad_to — дополнить файл текстовым чанком tEXt после IDAT до точного размера в байтах.
idat — готовые сжатые данные (для «бомбы»: заголовок обещает одно, данных другое).
"""
channels = 1 if gray else 3
@@ -43,9 +43,9 @@ def png(width, height, *, gray=False, noise=False, interlace=0, pad_to=None, ida
idat = b"".join(parts)
body = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", idat)
if pad_to is not None:
need = pad_to - len(body) - 12 - 12 # чанк-заполнитель + IEND
need = pad_to - len(body) - 12 - 12 - 8 # заголовок чанка-заполнителя, IEND, ключ "Comment\0"
assert need >= 0, "image is already larger than pad_to"
body += chunk(b"prVt", bytes(need))
body += chunk(b"tEXt", b"Comment\x00" + b"a" * need)
return body + chunk(b"IEND", b"")
@@ -72,3 +72,22 @@ def flip_byte(data: bytes, position: int) -> bytes:
GIF = b"GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;"
# --- сборка PNG из произвольных чанков (для проверок смысла чанков при верных CRC) ---
def ihdr(width, height, depth=8, color=2, interlace=0):
return b"IHDR", struct.pack(">IIBBBBB", width, height, depth, color, 0, 0, interlace)
def zero_idat(width, height, depth=8, channels=3):
"""Сжатые пиксели: каждая строка = байт фильтра 0 + нули (индекс палитры 0 / чёрный)."""
row_bytes = (width * depth * channels + 7) // 8
return b"IDAT", zlib.compress((b"\x00" + bytes(row_bytes)) * height)
def assemble(*chunks):
"""PNG из чанков (kind, data) с ВЕРНЫМИ CRC; IEND добавляется, если не передан."""
if not chunks or chunks[-1][0] != b"IEND":
chunks = chunks + ((b"IEND", b""),)
return b"\x89PNG\r\n\x1a\n" + b"".join(chunk(kind, data) for kind, data in chunks)