import struct from collections import Counter RANS_L = 1 << 31 def _build_freq(tokens): freq = Counter(tokens) max_sym = max(tokens) if tokens else 0 cum = [0] for i in range(max_sym + 1): cum.append(cum[-1] + freq.get(i, 0)) total = cum[-1] if total == 0: return {}, 0 table = {} for sym, f in freq.items(): table[sym] = (f, cum[sym]) return table, total def rans_encode(tokens): if not tokens: return b"" freq, total = _build_freq(tokens) if total == 0: return struct.pack("= RANS_L: out.append(state & 0xFFFF) state >>= 16 out.append(state & 0xFFFF) state >>= 16 if state: out.append(state) fbytes = struct.pack(f"<{len(out)}H", *out) meta = struct.pack("