Easier and more self documenting patterns for loading/saving Persistent
[python_utils.git] / letter_compress.py
1 #!/usr/bin/env python3
2
3 # © Copyright 2021-2022, Scott Gasch
4
5 """A simple toy compression helper for lowercase ascii text."""
6
7 import bitstring
8
9 from collect.bidict import BiDict
10
11 special_characters = BiDict(
12     {
13         ' ': 27,
14         '.': 28,
15         ',': 29,
16         "-": 30,
17         '"': 31,
18     }
19 )
20
21
22 def compress(uncompressed: str) -> bytes:
23     """Compress a word sequence into a stream of bytes.  The compressed
24     form will be 5/8th the size of the original.  Words can be lower
25     case letters or special_characters (above).
26
27     >>> import binascii
28     >>> binascii.hexlify(compress('this is a test'))
29     b'a2133da67b0ee859d0'
30
31     >>> binascii.hexlify(compress('scot'))
32     b'98df40'
33
34     >>> binascii.hexlify(compress('scott'))  # Note the last byte
35     b'98df4a00'
36
37     """
38     compressed = bitstring.BitArray()
39     for letter in uncompressed:
40         if 'a' <= letter <= 'z':
41             bits = ord(letter) - ord('a') + 1  # 1..26
42         else:
43             if letter not in special_characters:
44                 raise Exception(f'"{uncompressed}" contains uncompressable char="{letter}"')
45             bits = special_characters[letter]
46         compressed.append(f"uint:5={bits}")
47     while len(compressed) % 8 != 0:
48         compressed.append("uint:1=0")
49     return compressed.bytes
50
51
52 def decompress(kompressed: bytes) -> str:
53     """
54     Decompress a previously compressed stream of bytes back into
55     its original form.
56
57     >>> import binascii
58     >>> decompress(binascii.unhexlify(b'a2133da67b0ee859d0'))
59     'this is a test'
60
61     >>> decompress(binascii.unhexlify(b'98df4a00'))
62     'scott'
63
64     """
65     decompressed = ''
66     compressed = bitstring.BitArray(kompressed)
67
68     # There are compressed messages that legitimately end with the
69     # byte 0x00.  The message "scott" is an example; compressed it is
70     # 0x98df4a00.  It's 5 characters long which means there are 5 x 5
71     # bits of compressed info (25 bits, just over 3 bytes).  The last
72     # (25th) bit in the steam happens to be a zero.  The compress code
73     # padded out the compressed message by adding seven more zeros to
74     # complete the partial 4th byte.  In the 4th byte, however, one
75     # bit is information and seven are padding.
76     #
77     # It's likely that this API's client code may treat a zero byte as
78     # a termination character and not regard it as a legitimate part
79     # of the message.  This is a bug in that client code, to be clear.
80     #
81     # However, it's a bug we can work around:
82     #
83     # Here, I'm appending an extra 0x00 byte to the compressed message
84     # passed in.  If the client code dropped the last 0x00 byte (and,
85     # with it, some of the legitimate message bits) by treating it as
86     # a termination mark, this 0x00 will replace it (and the missing
87     # message bits).  If the client code didn't drop the last 0x00 (or
88     # if the compressed message didn't end in 0x00), adding an extra
89     # 0x00 is a no op because the codepoint 0b00000 is a "stop" message
90     # so we'll ignore the extras.
91     compressed.append("uint:8=0")
92
93     for chunk in compressed.cut(5):
94         chunk = chunk.uint
95         if chunk == 0:
96             break
97         elif 1 <= chunk <= 26:
98             letter = chr(chunk - 1 + ord('a'))
99         else:
100             letter = special_characters.inverse[chunk][0]
101         decompressed += letter
102     return decompressed
103
104
105 if __name__ == '__main__':
106     import doctest
107
108     doctest.testmod()