#!/usr/bin/env python3 """CC0: bounded liblz4 1.9.4 header/cursor controls, not a general decoder.""" import argparse import ctypes as C import datetime import importlib.util import json import pathlib import platform import struct BASE = pathlib.Path(__file__).parent SPEC = importlib.util.spec_from_file_location("frame_contract", BASE / "lz4-frame-contract.py") F = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(F) lib = F.lib lib.LZ4F_headerSize.argtypes = [C.c_void_p, C.c_size_t] lib.LZ4F_headerSize.restype = C.c_size_t lib.LZ4F_getFrameInfo.argtypes = [C.c_void_p, C.POINTER(F.FrameInfo), C.c_void_p, C.POINTER(C.c_size_t)] lib.LZ4F_getFrameInfo.restype = C.c_size_t def require(condition, message): if not condition: raise ValueError(message) def result(code): return {"error": lib.LZ4F_getErrorName(code).decode() if lib.LZ4F_isError(code) else None, "value": None if lib.LZ4F_isError(code) else code} def context(): ctx = C.c_void_p() F.checked(lib.LZ4F_createDecompressionContext(C.byref(ctx), 100)) return ctx def info(ctx, data): source = C.create_string_buffer(data) count, frame = C.c_size_t(len(data)), F.FrameInfo() observed = result(lib.LZ4F_getFrameInfo(ctx, C.byref(frame), source, C.byref(count))) return {**observed, "consumedBytes": count.value, "frameType": frame.frameType if observed["error"] is None else None, "contentSize": frame.contentSize if observed["error"] is None else None} def finish(ctx, data, offset, expected): require(type(offset) is int and 0 <= offset <= len(data), "invalid cursor") output, error, hint, calls = bytearray(), None, 1, 0 for _ in range(1000): source = C.create_string_buffer(data[offset:]) count = C.c_size_t(len(data) - offset) target, size = C.create_string_buffer(8192), C.c_size_t(8192) hint = lib.LZ4F_decompress(ctx, target, C.byref(size), source, C.byref(count), None) calls += 1 if lib.LZ4F_isError(hint): error = lib.LZ4F_getErrorName(hint).decode() break offset += count.value output.extend(target.raw[:size.value]) if hint == 0 or (count.value == 0 and size.value == 0): break else: raise ValueError("native call budget exhausted") return {"error": error, "frameComplete": error is None and hint == 0, "inputFullyConsumed": offset == len(data), "successfulCursorBytes": offset, "successfulCallOutputBytes": len(output), "exactPayload": bytes(output) == expected, "outputSha256": F.sha(output), "nativeCalls": calls} def fixtures(): normal = F.frame(content_checksum=True) require(normal[:4] == bytes.fromhex("04224d18") and normal[4] == 0x74, "unexpected normal fixture header") changed = {} for name, offset, mask in (("bad-header-checksum", 6, 1), ("reserved-flag", 4, 2), ("wrong-version", 4, 0xc0), ("bad-content-checksum", len(normal) - 4, 1)): data = bytearray(normal) data[offset] ^= mask changed[name] = bytes(data) return {"normal": normal, **changed, "five-byte-prefix": normal[:5], "skippable": struct.pack("