"""Bounded strict-codec observations, not an encoding detector.""" import argparse import hashlib import json from pathlib import Path import platform HERE = Path(__file__).resolve().parent def decode(raw, encoding): try: return [f"U+{ord(char):04X}" for char in raw.decode(encoding, errors="strict")] except UnicodeDecodeError: return "rejected" def observations(): rows = [] for raw in (b"A", b"\x00", b"\x7f", b"\x80", b"\xc3\xa9", b"\xff"): rows.append({"hex": raw.hex(" ").upper(), "ascii": decode(raw, "ascii"), "utf8": decode(raw, "utf-8")}) accepted = [value for value in range(256) if decode(bytes([value]), "ascii") != "rejected"] return {"single_byte_inputs": 256, "ascii_accepted": accepted, "ascii_rejected_count": 256 - len(accepted), "examples": rows} def main(): parser = argparse.ArgumentParser() parser.add_argument("--write", action="store_true") args = parser.parse_args() result = {"kind": "constructed-codec-examples", "environment": {"implementation": platform.python_implementation(), "python": platform.python_version()}, "probe_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "observations": observations()} target = HERE / "results.json" if args.write: target.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") else: saved = json.loads(target.read_text(encoding="utf-8")) if saved["observations"] != result["observations"]: raise RuntimeError("Recorded observations changed") if saved["probe_sha256"] != result["probe_sha256"]: raise RuntimeError("Recorded source hash changed") print(json.dumps({"pass": True, "single_byte_inputs": 256, "runtime": result["environment"]})) if __name__ == "__main__": main()