generated from mwc/lab_compression
49 lines
1.1 KiB
Python
49 lines
1.1 KiB
Python
|
|
|
|
from easybits import Bits
|
|
import codecs
|
|
|
|
def register_codec(encode, decode, name):
|
|
"""Registers a codec so that it can later be used to encode
|
|
or decode strings and bytes.
|
|
"""
|
|
def encode_wrapper(text):
|
|
return encode(text), len(text)
|
|
|
|
def decode_wrapper(data):
|
|
return decode(data), len(data)
|
|
|
|
def search_for_codec(query):
|
|
if query == name:
|
|
return codecs.CodecInfo(encode_wrapper, decode_wrapper, name=name)
|
|
|
|
codecs.register(search_for_codec)
|
|
|
|
|
|
CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ .,?!'"
|
|
|
|
def encode(text):
|
|
result = Bits()
|
|
text = text.upper()
|
|
|
|
for char in text:
|
|
if char in CHARS:
|
|
index = CHARS.index(char)
|
|
bits = Bits(index, length=5)
|
|
result = result.concat(bits)
|
|
|
|
return result.bytes
|
|
|
|
def decode(data):
|
|
bits = Bits(bytes(data))
|
|
text = ""
|
|
|
|
for i in range(0, len(bits), 5):
|
|
chunk = bits[i:i+5]
|
|
if len(chunk) == 5:
|
|
index = chunk.int
|
|
text += CHARS[index]
|
|
|
|
return text
|
|
|
|
register_codec(encode, decode, "trevcodec") |