"""Exact round-trip KT binary reference with a length header and byte termination."""
from pathlib import Path
from hashlib import sha256
import json,zlib

def bounds(n):
    return 1 << (n*8+(8*n+2).bit_length()+16)

def encode(raw):
    n=len(raw);end=bounds(n);start=0;zero=one=1
    for byte in raw:
        for shift in reversed(range(8)):
            split=start+(end-start)*zero//(zero+one)
            if not start<split<end:raise ArithmeticError("exhausted fixed-precision budget")
            if byte>>shift&1:start=split;one+=2
            else:end=split;zero+=2
    # Smallest whole-byte prefix whose zero-extended integer belongs to the interval.
    power=(bounds(n).bit_length()-1)
    for size in range((power+7)//8+1):
        scale=1<<(size*8)
        code=(start*scale+bounds(n)-1)//bounds(n)
        if code*bounds(n)<end*scale:
            return n.to_bytes(4,'big')+size.to_bytes(4,'big')+code.to_bytes(size,'big')
    raise ArithmeticError("termination failed")

def decode(stream):
    n=int.from_bytes(stream[:4],'big');end=bounds(n);start=0;zero=one=1
    length=int.from_bytes(stream[4:8],'big')
    if len(stream)!=8+length:raise ValueError('incorrect payload length')
    value=int.from_bytes(stream[8:],'big')*end//(1<<(8*length));out=bytearray()
    for _ in range(n):
        byte=0
        for _ in range(8):
            split=start+(end-start)*zero//(zero+one);bit=int(value>=split)
            if bit:start=split;one+=2
            else:end=split;zero+=2
            byte=(byte<<1)|bit
        out.append(byte)
    return bytes(out)

def run():
    corpus=Path(__file__).with_name('types09.py').read_bytes().replace(b'\r\n',b'\n')[:1024]
    results={}
    for label,data in [('source',corpus),('period4',bytes([0,0,1,1])*256),('empty',b''),('zeros',bytes(1024))]:
        stream=encode(data);assert decode(stream)==data
        results[label]=dict(original=len(data),kt_stream=len(stream),header=8,zlib=len(zlib.compress(data,6)),hash=sha256(data).hexdigest())
    return results
if __name__=='__main__':print(json.dumps(run(),indent=2))
