Skip to content

Commit 0cba811

Browse files
committed
Added codec: cobs
1 parent c0124a4 commit 0cba811

5 files changed

Lines changed: 130 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,7 @@ This category also contains `ascii85`, `adobe`, `[x]btoa`, `zeromq` with the `ba
317317
- [X] `bcd-extended0`: variant of `bcd` ; encodes characters from their (zero-left-padded) ordinals using prefix bits `0000`
318318
- [X] `bcd-extended1`: variant of `bcd` ; encodes characters from their (zero-left-padded) ordinals using prefix bits `1111`
319319
- [X] `chuck-norris`: Chuck Norris unary code (runs of the 7-bit ASCII bits written with blocks of zeros)
320+
- [X] `cobs`: aka Consistent Overhead Byte Stuffing ; removes the zero bytes of the data (with a variant adding the packet delimiter)
320321
- [X] `differential-manchester`: line code writing the bits as transitions at the start of their periods (also inverted)
321322
- [X] `elias-gamma`, `elias-delta`: Elias universal codes, encoding characters from their ordinals (or lists of integers with `-integers`)
322323
- [X] `excess3`: uses Excess-3 (aka Stibitz code) binary encoding to convert characters from their ordinals

‎docs/pages/enc/binary.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,30 @@ Each character is written with the 7 bits of its ASCII code, then the resulting
9898

9999
-----
100100

101+
### Consistent Overhead Byte Stuffing (COBS)
102+
103+
[COBS](https://en.wikipedia.org/wiki/Consistent_Overhead_Byte_Stuffing) removes the zero bytes of the data, so that a zero byte can delimit packets: each block of non-zero bytes is preceded by a code byte giving its length plus one (the distance to the next zero byte), a block of 254 bytes being written with the code 255 and followed by no zero byte. The overhead is of 1 byte per 254 bytes at most. As CyberChef, encoding does not add the zero byte delimiting the packet and decoding rejects any zero byte ; the `-delimited` variant adds it when encoding and requires it when decoding.
104+
105+
**Codec** | **Conversions** | **Aliases** | **Comment**
106+
:---: | :---: | --- | ---
107+
`cobs` | data <-> COBS encoded data | `consistent-overhead-byte-stuffing` | without the packet delimiter
108+
`cobs-delimited` | data <-> COBS encoded packet | `cobs_delimited` | with the packet delimiter (a final zero byte)
109+
110+
```python
111+
>>> codext.encode(b"\x11\x22\x00\x33", "cobs")
112+
b'\x03\x11"\x023'
113+
>>> codext.encode(b"\x11\x22\x00\x33", "cobs-delimited")
114+
b'\x03\x11"\x023\x00'
115+
>>> codext.decode(b"\x03\x11\x22\x02\x33", "cobs")
116+
b'\x11"\x003'
117+
```
118+
119+
!!! note "Guessing"
120+
121+
As the COBS encoding of a data without zero byte only differs from it by a code byte every 254 bytes, guessing it relies on the structure of the code bytes only, hence it is not reliably ranked first.
122+
123+
-----
124+
101125
### Elias Gamma/Delta Codes
102126

103127
These universal codes write positive integers as self-delimiting codewords, hence concatenated without separator:

‎src/codext/binary/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from .baudot import *
33
from .bcd import *
44
from .chucknorris import *
5+
from .cobs import *
56
from .elias import *
67
from .excess3 import *
78
from .fibonacci import *

‎src/codext/binary/cobs.py‎

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
# -*- coding: UTF-8 -*-
2+
"""COBS Codec - Consistent Overhead Byte Stuffing content encoding.
3+
4+
Consistent Overhead Byte Stuffing (COBS), by Stuart Cheshire and Mary Baker (1999), removes the zero bytes of the data,
5+
so that a zero byte can be used to delimit packets: the data is split at its zero bytes, each block being preceded by a
6+
code byte giving its length plus one (hence the distance to the next zero byte), a block of 254 non-zero bytes being
7+
written with the code 255 and followed by no zero byte. The overhead is of 1 byte per 254 bytes at most.
8+
9+
Encoding does not add the zero byte delimiting the packet, as CyberChef, and decoding rejects any zero byte, while the
10+
"-delimited" variant adds it after the encoded data and requires it when decoding.
11+
12+
This codec:
13+
- en/decodes strings from str to str
14+
- en/decodes strings from bytes to bytes
15+
- decodes file content to str (read)
16+
- encodes file content from str to bytes (write)
17+
18+
Reference: https://en.wikipedia.org/wiki/Consistent_Overhead_Byte_Stuffing
19+
"""
20+
from ..__common__ import *
21+
22+
23+
__examples__ = {
24+
# examples of Wikipedia (without the delimiter)
25+
'enc(cobs|consistent-overhead-byte-stuffing)': {
26+
'\x00': "\x01\x01", '\x00\x00': "\x01\x01\x01", '\x00\x11\x00': "\x01\x02\x11\x01",
27+
'\x11\x22\x00\x33': "\x03\x11\x22\x02\x33", '\x11\x22\x33\x44': "\x05\x11\x22\x33\x44",
28+
'\x11\x00\x00\x00': "\x02\x11\x01\x01\x01", '': "",
29+
"".join(map(chr, range(1, 255))): "\xff" + "".join(map(chr, range(1, 255))),
30+
"".join(map(chr, range(0, 255))): "\x01\xff" + "".join(map(chr, range(1, 255))),
31+
"".join(map(chr, range(1, 256))): "\xff" + "".join(map(chr, range(1, 255))) + "\x02\xff",
32+
"".join(map(chr, range(2, 256))) + "\x00": "\xff" + "".join(map(chr, range(2, 256))) + "\x01\x01",
33+
"".join(map(chr, range(3, 256))) + "\x00\x01": "\xfe" + "".join(map(chr, range(3, 256))) + "\x02\x01",
34+
},
35+
'enc(cobs-delimited|cobs_delimited)': {'\x11\x22\x00\x33': "\x03\x11\x22\x02\x33\x00"},
36+
'dec(cobs)': {'\x03\x11\x22\x02\x33': "\x11\x22\x00\x33", '\x00HELLO': None, 'HE\x00LLO': None, 'HELLO\x00': None,
37+
'\x05\x11\x22': None},
38+
'dec(cobs-delimited)': {'\x03\x11\x22\x02\x33\x00': "\x11\x22\x00\x33", '\x03\x11\x22\x02\x33': None,
39+
'\x03\x11\x00\x02\x33\x00': None},
40+
'enc-dec(cobs|cobs-delimited)': ["test", "This is a test", "\x00\x00\x00", "@random{512,1024,2048}"],
41+
}
42+
__guess__ = ["cobs", "cobs-delimited"]
43+
44+
45+
def cobs_encode(delimited=""):
46+
def encode(text, errors="strict"):
47+
t, r, block = b(text), bytearray(), bytearray()
48+
# each block of non-zero bytes ending at a zero byte is preceded by its length plus one, while a block of 254
49+
# bytes is preceded by 255 and is not followed by a zero byte
50+
for byte in t:
51+
if byte == 0:
52+
r += bytes([len(block) + 1]) + block
53+
block = bytearray()
54+
continue
55+
block.append(byte)
56+
if len(block) == 254:
57+
r += b"\xff" + block
58+
block = bytearray()
59+
# the data is seen as followed by a zero byte (not written), ending a last block unless the data ends with a
60+
# block of 254 bytes
61+
if block or t[-1:] == b"\x00":
62+
r += bytes([len(block) + 1]) + block
63+
return bytes(r) + (b"\x00" if delimited else b""), len(t)
64+
return encode
65+
66+
67+
def cobs_decode(delimited=""):
68+
def decode(text, errors="strict"):
69+
t, _h, r = b(text), handle_error("cobs", errors, decode=True, kind="byte"), bytearray()
70+
if delimited:
71+
# the packet must be delimited by a zero byte, which is removed
72+
if t[-1:] != b"\x00":
73+
_h(t[-1:], len(t) - 1)
74+
else:
75+
t = t[:-1]
76+
if b"\x00" in t:
77+
# no zero byte is allowed in the encoded data
78+
i = t.index(b"\x00")
79+
_h(t[i:i+1], i)
80+
t = t.replace(b"\x00", b"")
81+
i = 0
82+
while i < len(t):
83+
code = t[i]
84+
block = t[i+1:i+code]
85+
if len(block) < code - 1:
86+
# the block is cut by the end of the data
87+
_h(t[i:i+1], i, bytes(r))
88+
r += block
89+
i += code
90+
if code < 255 and i < len(t):
91+
r.append(0)
92+
return bytes(r), len(text)
93+
return decode
94+
95+
96+
add("cobs", cobs_encode, cobs_decode, r"^(?:cobs|consistent[-_]overhead[-_]byte[-_]stuffing)([-_]delimited)?$",
97+
expansion_factor=(1., .1))

‎tests/test_manual.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,13 @@ def test_codec_coquelet(self):
5858
self.assertEqual(codecs.decode("960 773 960 826 960", "coquelet8", "ignore"), "MT")
5959
self.assertEqual(len(codecs.encode("A1B2", "coquelet").split()), 2 * 7)
6060

61+
def test_codec_cobs(self):
62+
# the output holds no zero byte, the zero bytes being removed when decoding if errors are not handled strictly
63+
self.assertNotIn(b"\x00", codecs.encode(b"\x00" * 300 + bytes(range(256)) * 3, "cobs"))
64+
self.assertEqual(codecs.decode(b"\x03\x11\x22\x00\x02\x33", "cobs", "ignore"), b"\x11\x22\x00\x33")
65+
# a missing delimiter is tolerated if errors are not handled strictly
66+
self.assertEqual(codecs.decode(b"\x03\x11\x22", "cobs-delimited", "ignore"), b"\x11\x22")
67+
6168
def test_codec_cow(self):
6269
# with a non-strict errors handling, other characters are comments and the program stops at a failing
6370
# instruction

0 commit comments

Comments
 (0)