Something went wrong. Try again.
Converting between UTF-8 and legacy character encodings, as the WHATWG Encoding Standard and glibc's iconv define them.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243# SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us># SPDX-License-Identifier: MIT
"""Diff this library against Python's codecs module.
The tables under ``src/tables`` are generated from the index files in``data``, so a test written against those tables proves only that thegenerator and the codecs agree with each other. This asks a secondimplementation -- CPython's, written from the same underlying standards bysomebody else -- the same questions, and prints where the two disagree.
Disagreement is not automatically a bug. The Encoding Standard deliberatelydeparts from the registered definition of several encodings in order to matchdeployed content, and each such departure shows up here. The point is to havethe list be short, explained, and stable, rather than to have it be empty; theREADME's "differences from other implementations" section is the explanation,and a difference that is not accounted for there is a finding.
One difference outside the standard's doing is CP875 encoding U+001A,where this library writes 0x3F and CPython writes 0xFD. Microsoft's tablespells six unassigned positions as SUBSTITUTE alongside the real one, and 0x3Fis the position every other EBCDIC page uses -- including, in CPython, cp037,cp500 and cp1026.
The Korean encodings outside the standard differ from CPython in ways theREADME sets out: Johab's decoder here refuses the sixteen final-positionspellings of a jamo, and 84 41, that JOHAB.TXT leaves out, and Wansungdecodes A4 D4 that does not begin an eight-byte syllable as the Hangul fillerwhere CPython reports an error and loses step with the pairs after it.
nix develop -c python3 tools/crosscheck.py # every encoding nix develop -c python3 tools/crosscheck.py shift_jis # just one"""
from __future__ import annotations
import subprocessimport sysfrom dataclasses import dataclass, field
# The label to hand this library, and the codec name to ask Python for.CODECS = { "ibm866": "cp866", "iso-8859-2": "iso8859_2", "iso-8859-3": "iso8859_3", "iso-8859-4": "iso8859_4", "iso-8859-5": "iso8859_5", "iso-8859-6": "iso8859_6", "iso-8859-7": "iso8859_7", "iso-8859-8": "iso8859_8", "iso-8859-10": "iso8859_10", "iso-8859-13": "iso8859_13", "iso-8859-14": "iso8859_14", "iso-8859-15": "iso8859_15", "iso-8859-16": "iso8859_16", "koi8-r": "koi8_r", "koi8-u": "koi8_u", "macintosh": "mac_roman", "windows-874": "cp874", "windows-1250": "cp1250", "windows-1251": "cp1251", "windows-1252": "cp1252", "windows-1253": "cp1253", "windows-1254": "cp1254", "windows-1255": "cp1255", "windows-1256": "cp1256", "windows-1257": "cp1257", "windows-1258": "cp1258", "x-mac-cyrillic": "mac_cyrillic", "shift_jis": "cp932", "euc-jp": "euc_jp", "euc-kr": "cp949", "gbk": "gbk", "gb18030": "gb18030", "big5": "big5hkscs", "utf-8": "utf_8", "utf-16le": "utf_16_le", "utf-16be": "utf_16_be", # EBCDIC, which is not in the standard and is named here by its enum # member rather than by a label -- it deliberately has none. "cp037": "cp037", "cp500": "cp500", "cp875": "cp875", "cp1026": "cp1026", # Korean encodings outside the standard, likewise named by enum member. "wansung": "euc_kr", "johab": "johab",}
# Two bytes is enough to reach every multi-byte encoding's main plane; only# gb18030's four-byte form needs more, and it is checked from the code point# side instead.TWO_BYTE = { "shift_jis", "euc-jp", "euc-kr", "gbk", "gb18030", "big5", "utf-8", "utf-16le", "utf-16be", "wansung", "johab",}
@dataclassclass Report: label: str mode: str total: int = 0 differences: list[tuple[str, str, str]] = field(default_factory=list)
DECODE_ONLY = "# decode-only"
class Unavailable(Exception): """The Zig side could not answer, and said why."""
def ours(label: str, mode: str) -> list[tuple[str, str]]: """Run the Zig side and parse `input<TAB>result` lines.
Raises `Unavailable` rather than propagating a failed build, so that one encoding cannot discard a run that has already done several minutes of work on the others. """ result = subprocess.run( ["zig", "build", "crosscheck", "--", label, mode], capture_output=True, text=True, ) if result.returncode != 0: detail = (result.stderr or result.stdout).strip().splitlines() raise Unavailable(detail[0] if detail else f"exit {result.returncode}")
out = [] for line in result.stdout.splitlines(): if not line: continue # The standard makes utf-16le, utf-16be and replacement decode-only. # The Zig side says so rather than failing, because "there is no # encoder" is the right answer to the question and not a fault. if line == DECODE_ONLY: raise Unavailable("decode-only: the standard defines no encoder") key, _, value = line.partition("\t") out.append((key, value)) return out
def theirs_decode(codec: str, raw: bytes) -> str: try: text = raw.decode(codec, errors="strict") except UnicodeDecodeError: return "ERR" if not text: return "-" return ",".join(format(ord(c), "x") for c in text)
def theirs_encode(codec: str, code_point: int) -> str: try: raw = chr(code_point).encode(codec, errors="strict") except (UnicodeEncodeError, UnicodeError): return "ERR" if not raw: return "-" return raw.hex()
def is_syllable(result: str) -> bool: return "," not in result and result not in ("ERR", "-") and 0xAC00 <= int(result, 16) <= 0xD7A3
def check(label: str, codec: str, mode: str) -> Report: report = Report(label, mode) for key, mine in ours(label, mode): if mode == "encode": yours = theirs_encode(codec, int(key, 16)) else: yours = theirs_decode(codec, bytes.fromhex(key)) report.total += 1 # An eight-byte sequence that is not a syllable is the filler and # whatever follows it here, and an error that knocks CPython's # decoder out of step with the pairs after it; those are bound to # differ, and the README says why. What has to agree is which # sequences are syllables, and which syllable each one is. if mode == "syllables" and not (is_syllable(mine) or is_syllable(yours)): continue if mine != yours: report.differences.append((key, mine, yours)) return report
def main(argv: list[str]) -> int: wanted = argv[1:] or list(CODECS) worst = 0 skipped: list[tuple[str, str, str]] = [] for label in wanted: codec = CODECS[label] modes = ["decode1", "encode"] if label in TWO_BYTE: modes.insert(1, "decode2") if label == "wansung": modes.append("syllables") for mode in modes: try: report = check(label, codec, mode) except Unavailable as why: print(f"{label:16s} {mode:8s} vs {codec:12s} skipped -- {why}") skipped.append((label, mode, str(why))) continue count = len(report.differences) worst = max(worst, count) print(f"{label:16s} {mode:8s} vs {codec:12s} {count:7d} / {report.total} differ") for key, mine, yours in report.differences[:8]: print(f" {key:8s} ours={mine:20s} python={yours}") if count > 8: print(f" ... and {count - 8} more")
# Differences do not fail the run: the standard departs from the # registered definitions on purpose, so the list is meant to be short and # explained rather than empty, and the README is where it is explained. # # Something the Zig side could not answer *does* fail it, unless the # reason was that the encoding has no encoder -- which is the standard's # own decision about utf-16le, utf-16be and replacement, and not a fault. unexpected = [s for s in skipped if not s[2].startswith("decode-only")] if skipped: print() for label, mode, why in skipped: print(f"skipped: {label} {mode} -- {why}") if unexpected: print(f"{len(unexpected)} could not be run; that is a finding, not a skip") return 1 return 0
if __name__ == "__main__": sys.exit(main(sys.argv))