Created
January 9, 2019 05:05
-
-
Save rsaxvc/7c9700e065a0e4a62968dac559448966 to your computer and use it in GitHub Desktop.
Low-Overhead COBS Encoder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#COBS encoder using minimal buffer instead of encoding entire buffer at once | |
#Passes unit tests from Wikipedia page | |
class cobsEncoder: | |
def __init__(self): | |
self.cobsBuffer = b'' | |
self.postZero = False | |
def encode(self,data): | |
for d in data: | |
if d == b'\x00': | |
yield len(self.cobsBuffer)+1 | |
for c in self.cobsBuffer: | |
yield ord(c) | |
self.cobsBuffer = b'' | |
self.postZero = True | |
else: | |
self.cobsBuffer = self.cobsBuffer + d | |
self.postZero = False | |
if len(self.cobsBuffer) == 0xFE: | |
yield 0xFF | |
for c in self.cobsBuffer: | |
yield ord(c) | |
self.cobsBuffer = b'' | |
def flush(self): | |
if len(self.cobsBuffer) > 0: | |
yield len(self.cobsBuffer) + 1 | |
for c in self.cobsBuffer: | |
yield ord(c) | |
if self.postZero: | |
yield 1 | |
self.cobsBuffer = b'' | |
def encodeAndFlush(self, data): | |
for c in self.encode(data): | |
yield c | |
for c in self.flush(): | |
yield c | |
def encodeAndPrint(data): | |
c = cobsEncoder() | |
for x in c.encodeAndFlush(data): | |
print hex(x), | |
print '' | |
def encodeAndPrintRange(start,stop): | |
c = cobsEncoder() | |
for b in range(start,stop+1): | |
for x in c.encode(b''+chr(b)): | |
print hex(x), | |
for x in c.flush(): | |
print hex(x), | |
print '' | |
print '' | |
def encodeAndPrintList(l): | |
c = cobsEncoder() | |
for b in l: | |
for x in c.encode(b''+chr(b)): | |
print hex(x), | |
for x in c.flush(): | |
print hex(x), | |
print '' | |
print '' | |
encodeAndPrint(b'\x00') | |
encodeAndPrint(b'\x00\x00') | |
encodeAndPrint(b'\x11\x22\x00\x33') | |
encodeAndPrint(b'\x11\x22\x33\x44') | |
encodeAndPrint(b'\x11\x00\x00\x00') | |
encodeAndPrintRange(0x01, 0xFE ) | |
encodeAndPrintRange(0x00, 0xFE ) | |
encodeAndPrintRange(0x01, 0xFF ) | |
encodeAndPrintList( range(0x02,0x100) + range(1) ) | |
encodeAndPrintList( range(0x03,0x100) + range(2) ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment