-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcodecs_incremental_zlib.py
More file actions
53 lines (42 loc) · 1.24 KB
/
codecs_incremental_zlib.py
File metadata and controls
53 lines (42 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import codecs
import sys
from module_codecs.codecs_to_hex import to_hex
text = b"abcdefghijklmnopqrstuvwxyz\n"
repetitions = 50
print("Txt length: ", len(text))
print("Repetitions: ", repetitions)
print("Expected len: ", len(text) * repetitions)
# Encode the text several times to build up a large amount of data
encoder = codecs.getincrementalencoder("zlib")()
encoded = []
print()
print("Encoding: ", end=" ")
last = repetitions - 1
for i in range(repetitions):
en_c = encoder.encode(text, final=(i == last))
if en_c:
print("\nEncoded: {} bytes".format(len(en_c)))
encoded.append(en_c)
else:
sys.stdout.write(".")
all_encoded = b"".join(encoded)
print()
print("Total encoded length: ", len(all_encoded))
print()
# Decode the byte string one byte at a time
decoder = codecs.getincrementaldecoder("zlib")()
decoded = []
print("Decoding: ", end=" ")
for i, b in enumerate(all_encoded):
final = (i + 1) == len(text)
c = decoder.decode(bytes([b]), final)
if c:
print("\nDecoded: {} characters".format(len(c)))
print("Decoding: ", end=" ")
decoded.append(c)
else:
sys.stdout.write(".")
print()
restored = b"".join(decoded)
print()
print("Total uncompressed length: ", len(restored))