From 9e5e63c2c62f24f0d633b8c380207a14d9011add Mon Sep 17 00:00:00 2001 From: Marc Olivier Chouinard Date: Sun, 10 May 2020 15:33:49 -0400 Subject: [PATCH] Implement Uint8 encoding compressToUint8Array decompressToUint8Array This is the best I could do without doing a bigger rewrite so lzstringn doesn't use the str() type and use bytes() (or another type). str() have lot of issues with conversions. --- lzstring/__init__.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/lzstring/__init__.py b/lzstring/__init__.py index a264411..cf91d62 100644 --- a/lzstring/__init__.py +++ b/lzstring/__init__.py @@ -50,7 +50,10 @@ def _compress(uncompressed, bitsPerChar, getCharFromInt): context_data_position = 0 for ii in range(len(uncompressed)): - context_c = uncompressed[ii] + if isinstance(uncompressed, (bytes)): + context_c = chr(uncompressed[ii]) + else: + context_c = uncompressed[ii] if context_c not in context_dictionary: context_dictionary[context_c] = context_dictSize context_dictSize += 1 @@ -373,6 +376,11 @@ class LZString(object): def compress(uncompressed): return _compress(uncompressed, 16, chr) + @staticmethod + def compressToUint8Array(uncompressed): + return bytes([ord(x) for x in _compress(uncompressed, 8, chr)]) + + @staticmethod def compressToUTF16(uncompressed): if uncompressed is None: @@ -404,6 +412,14 @@ def decompress(compressed): return None return _decompress(len(compressed), 32768, lambda index: ord(compressed[index])) + @staticmethod + def decompressFromUint8Array(compressed): + if compressed is None: + return "" + if compressed == "": + return None + return _decompress(len(compressed), 128, lambda index: compressed[index]) + @staticmethod def decompressFromUTF16(compressed): if compressed is None: