cobs 1.2.3__cp315-cp315-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cobs/__init__.py +17 -0
- cobs/_version/__init__.py +22 -0
- cobs/cobs/__init__.py +42 -0
- cobs/cobs/_cobs_ext.cp315-win_amd64.pyd +0 -0
- cobs/cobs/_cobs_py.py +91 -0
- cobs/cobs/test.py +225 -0
- cobs/cobsr/__init__.py +35 -0
- cobs/cobsr/_cobsr_ext.cp315-win_amd64.pyd +0 -0
- cobs/cobsr/_cobsr_py.py +99 -0
- cobs/cobsr/test.py +258 -0
- cobs-1.2.3.dist-info/METADATA +312 -0
- cobs-1.2.3.dist-info/RECORD +15 -0
- cobs-1.2.3.dist-info/WHEEL +5 -0
- cobs-1.2.3.dist-info/licenses/LICENSE.txt +22 -0
- cobs-1.2.3.dist-info/top_level.txt +1 -0
cobs/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Consistent Overhead Byte Stuffing (COBS)
|
|
2
|
+
|
|
3
|
+
Encoding and decoding functions for COBS and variants.
|
|
4
|
+
|
|
5
|
+
The following sub-modules are provided:
|
|
6
|
+
|
|
7
|
+
* ``cobs.cobs`` which implements plain COBS.
|
|
8
|
+
* ``cobs.cobsr`` which implements COBS/Reduced.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
__all__ = [ 'cobs', 'cobsr', ]
|
|
12
|
+
|
|
13
|
+
#from . import cobs
|
|
14
|
+
#from . import cobsr
|
|
15
|
+
|
|
16
|
+
from ._version import *
|
|
17
|
+
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""
|
|
2
|
+
_version
|
|
3
|
+
|
|
4
|
+
Version information for cobs.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
'VERSION_MAJOR',
|
|
9
|
+
'VERSION_MINOR',
|
|
10
|
+
'VERSION_PATCH',
|
|
11
|
+
'VERSION_STRING',
|
|
12
|
+
'__version__',
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
VERSION_MAJOR = 1
|
|
16
|
+
VERSION_MINOR = 2
|
|
17
|
+
VERSION_PATCH = 3
|
|
18
|
+
|
|
19
|
+
VERSION_STRING = '%s.%s.%s' % (VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH)
|
|
20
|
+
|
|
21
|
+
__version__ = VERSION_STRING
|
|
22
|
+
|
cobs/cobs/__init__.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Consistent Overhead Byte Stuffing (COBS) encoding and decoding.
|
|
3
|
+
|
|
4
|
+
Functions are provided for encoding and decoding according to
|
|
5
|
+
the basic COBS method.
|
|
6
|
+
|
|
7
|
+
The COBS variant "Zero Pair Elimination" (ZPE) is not
|
|
8
|
+
implemented.
|
|
9
|
+
|
|
10
|
+
A pure Python implementation and a C extension implementation
|
|
11
|
+
are provided. If the C extension is not available for some reason,
|
|
12
|
+
the pure Python version will be used.
|
|
13
|
+
|
|
14
|
+
References:
|
|
15
|
+
http://www.stuartcheshire.org/papers/COBSforToN.pdf
|
|
16
|
+
http://tools.ietf.org/html/draft-ietf-pppext-cobs-00
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
try:
|
|
20
|
+
from ._cobs_ext import *
|
|
21
|
+
_using_extension = True
|
|
22
|
+
except ImportError:
|
|
23
|
+
from ._cobs_py import *
|
|
24
|
+
_using_extension = False
|
|
25
|
+
|
|
26
|
+
DecodeError.__module__ = 'cobs.cobs'
|
|
27
|
+
|
|
28
|
+
from .._version import *
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def encoding_overhead(source_len):
|
|
32
|
+
"""Calculates the maximum overhead when encoding a message with the given length.
|
|
33
|
+
The overhead is a maximum of [n/254] bytes (one in 254 bytes) rounded up."""
|
|
34
|
+
if source_len == 0:
|
|
35
|
+
return 1
|
|
36
|
+
return (source_len + 253) // 254
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def max_encoded_length(source_len):
|
|
40
|
+
"""Calculates how maximum possible size of an encoded message given the length of the
|
|
41
|
+
source message."""
|
|
42
|
+
return source_len + encoding_overhead(source_len)
|
|
Binary file
|
cobs/cobs/_cobs_py.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Consistent Overhead Byte Stuffing (COBS)
|
|
3
|
+
|
|
4
|
+
This version is for Python 3.x.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class DecodeError(Exception):
|
|
9
|
+
pass
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _get_buffer_view(in_bytes):
|
|
13
|
+
mv = memoryview(in_bytes)
|
|
14
|
+
if mv.ndim > 1 or mv.itemsize > 1:
|
|
15
|
+
raise BufferError('object must be a single-dimension buffer of bytes.')
|
|
16
|
+
try:
|
|
17
|
+
if mv.format != 'B':
|
|
18
|
+
mv = mv.cast('B')
|
|
19
|
+
except AttributeError:
|
|
20
|
+
pass
|
|
21
|
+
return mv
|
|
22
|
+
|
|
23
|
+
def encode(in_bytes):
|
|
24
|
+
"""Encode a string using Consistent Overhead Byte Stuffing (COBS).
|
|
25
|
+
|
|
26
|
+
Input is any byte string. Output is also a byte string.
|
|
27
|
+
|
|
28
|
+
Encoding guarantees no zero bytes in the output. The output
|
|
29
|
+
string will be expanded slightly, by a predictable amount.
|
|
30
|
+
|
|
31
|
+
An empty string is encoded to '\\x01'"""
|
|
32
|
+
if isinstance(in_bytes, str):
|
|
33
|
+
raise TypeError('Unicode-objects must be encoded as bytes first')
|
|
34
|
+
in_bytes_mv = _get_buffer_view(in_bytes)
|
|
35
|
+
final_zero = True
|
|
36
|
+
out_bytes = bytearray()
|
|
37
|
+
idx = 0
|
|
38
|
+
search_start_idx = 0
|
|
39
|
+
for in_char in in_bytes_mv:
|
|
40
|
+
if in_char == 0:
|
|
41
|
+
final_zero = True
|
|
42
|
+
out_bytes.append(idx - search_start_idx + 1)
|
|
43
|
+
out_bytes += in_bytes_mv[search_start_idx:idx]
|
|
44
|
+
search_start_idx = idx + 1
|
|
45
|
+
else:
|
|
46
|
+
if idx - search_start_idx == 0xFD:
|
|
47
|
+
final_zero = False
|
|
48
|
+
out_bytes.append(0xFF)
|
|
49
|
+
out_bytes += in_bytes_mv[search_start_idx:idx+1]
|
|
50
|
+
search_start_idx = idx + 1
|
|
51
|
+
idx += 1
|
|
52
|
+
if idx != search_start_idx or final_zero:
|
|
53
|
+
out_bytes.append(idx - search_start_idx + 1)
|
|
54
|
+
out_bytes += in_bytes_mv[search_start_idx:idx]
|
|
55
|
+
return bytes(out_bytes)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def decode(in_bytes):
|
|
59
|
+
"""Decode a string using Consistent Overhead Byte Stuffing (COBS).
|
|
60
|
+
|
|
61
|
+
Input should be a byte string that has been COBS encoded. Output
|
|
62
|
+
is also a byte string.
|
|
63
|
+
|
|
64
|
+
A cobs.DecodeError exception will be raised if the encoded data
|
|
65
|
+
is invalid."""
|
|
66
|
+
if isinstance(in_bytes, str):
|
|
67
|
+
raise TypeError('Unicode-objects are not supported; byte buffer objects only')
|
|
68
|
+
in_bytes_mv = _get_buffer_view(in_bytes)
|
|
69
|
+
out_bytes = bytearray()
|
|
70
|
+
idx = 0
|
|
71
|
+
|
|
72
|
+
if len(in_bytes_mv) > 0:
|
|
73
|
+
while True:
|
|
74
|
+
length = in_bytes_mv[idx]
|
|
75
|
+
if length == 0:
|
|
76
|
+
raise DecodeError("zero byte found in input")
|
|
77
|
+
idx += 1
|
|
78
|
+
end = idx + length - 1
|
|
79
|
+
copy_mv = in_bytes_mv[idx:end]
|
|
80
|
+
if 0 in copy_mv:
|
|
81
|
+
raise DecodeError("zero byte found in input")
|
|
82
|
+
out_bytes += copy_mv
|
|
83
|
+
idx = end
|
|
84
|
+
if idx > len(in_bytes_mv):
|
|
85
|
+
raise DecodeError("not enough input bytes for length code")
|
|
86
|
+
if idx < len(in_bytes_mv):
|
|
87
|
+
if length < 0xFF:
|
|
88
|
+
out_bytes.append(0)
|
|
89
|
+
else:
|
|
90
|
+
break
|
|
91
|
+
return bytes(out_bytes)
|
cobs/cobs/test.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Consistent Overhead Byte Stuffing (COBS)
|
|
3
|
+
|
|
4
|
+
Unit Tests
|
|
5
|
+
|
|
6
|
+
This version is for Python 3.x.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from array import array
|
|
10
|
+
import random
|
|
11
|
+
import unittest
|
|
12
|
+
|
|
13
|
+
from .. import cobs as cobs
|
|
14
|
+
#from ..cobs import _cobs_py as cobs
|
|
15
|
+
|
|
16
|
+
def infinite_non_zero_generator():
|
|
17
|
+
while True:
|
|
18
|
+
for i in range(1,50):
|
|
19
|
+
for j in range(1,256, i):
|
|
20
|
+
yield j
|
|
21
|
+
|
|
22
|
+
def non_zero_generator(length):
|
|
23
|
+
non_zeros = infinite_non_zero_generator()
|
|
24
|
+
for i in range(length):
|
|
25
|
+
yield next(non_zeros)
|
|
26
|
+
|
|
27
|
+
def non_zero_bytes(length):
|
|
28
|
+
return b''.join(bytes([i]) for i in non_zero_generator(length))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class PredefinedEncodingsTests(unittest.TestCase):
|
|
32
|
+
predefined_encodings = [
|
|
33
|
+
[ b"", b"\x01" ],
|
|
34
|
+
[ b"1", b"\x021" ],
|
|
35
|
+
[ b"12345", b"\x0612345" ],
|
|
36
|
+
[ b"12345\x006789", b"\x0612345\x056789" ],
|
|
37
|
+
[ b"\x0012345\x006789", b"\x01\x0612345\x056789" ],
|
|
38
|
+
[ b"12345\x006789\x00", b"\x0612345\x056789\x01" ],
|
|
39
|
+
[ b"\x00", b"\x01\x01" ],
|
|
40
|
+
[ b"\x00\x00", b"\x01\x01\x01" ],
|
|
41
|
+
[ b"\x00\x00\x00", b"\x01\x01\x01\x01" ],
|
|
42
|
+
[ bytes(bytearray(range(1, 254))), bytes(b"\xfe" + bytearray(range(1, 254))) ],
|
|
43
|
+
[ bytes(bytearray(range(1, 255))), bytes(b"\xff" + bytearray(range(1, 255))) ],
|
|
44
|
+
[ bytes(bytearray(range(1, 256))), bytes(b"\xff" + bytearray(range(1, 255)) + b"\x02\xff") ],
|
|
45
|
+
[ bytes(bytearray(range(0, 256))), bytes(b"\x01\xff" + bytearray(range(1, 255)) + b"\x02\xff") ],
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
def test_predefined_encodings(self):
|
|
49
|
+
for (test_string, expected_encoded_string) in self.predefined_encodings:
|
|
50
|
+
encoded = cobs.encode(test_string)
|
|
51
|
+
self.assertEqual(encoded, expected_encoded_string)
|
|
52
|
+
|
|
53
|
+
def test_decode_predefined_encodings(self):
|
|
54
|
+
for (test_string, expected_encoded_string) in self.predefined_encodings:
|
|
55
|
+
decoded = cobs.decode(expected_encoded_string)
|
|
56
|
+
self.assertEqual(test_string, decoded)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class PredefinedDecodeErrorTests(unittest.TestCase):
|
|
60
|
+
decode_error_test_strings = [
|
|
61
|
+
b"\x00",
|
|
62
|
+
b"\x05123",
|
|
63
|
+
b"\x051234\x00",
|
|
64
|
+
b"\x0512\x004",
|
|
65
|
+
]
|
|
66
|
+
|
|
67
|
+
def test_predefined_decode_error(self):
|
|
68
|
+
for test_encoded in self.decode_error_test_strings:
|
|
69
|
+
with self.assertRaises(cobs.DecodeError):
|
|
70
|
+
cobs.decode(test_encoded)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class ZerosTest(unittest.TestCase):
|
|
74
|
+
def test_zeros(self):
|
|
75
|
+
for length in range(520):
|
|
76
|
+
test_string = b'\x00' * length
|
|
77
|
+
encoded = cobs.encode(test_string)
|
|
78
|
+
expected_encoded = b'\x01' * (length + 1)
|
|
79
|
+
self.assertEqual(encoded, expected_encoded, "encoding zeros failed for length %d" % length)
|
|
80
|
+
decoded = cobs.decode(encoded)
|
|
81
|
+
self.assertEqual(decoded, test_string, "decoding zeros failed for length %d" % length)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class NonZerosTest(unittest.TestCase):
|
|
85
|
+
def simple_encode_non_zeros_only(self, in_bytes):
|
|
86
|
+
out_list = []
|
|
87
|
+
for i in range(0, len(in_bytes), 254):
|
|
88
|
+
data_block = in_bytes[i: i+254]
|
|
89
|
+
out_list.append(bytes([ len(data_block) + 1 ]))
|
|
90
|
+
out_list.append(data_block)
|
|
91
|
+
return b''.join(out_list)
|
|
92
|
+
|
|
93
|
+
def test_non_zeros(self):
|
|
94
|
+
for length in range(1, 1000):
|
|
95
|
+
test_string = non_zero_bytes(length)
|
|
96
|
+
encoded = cobs.encode(test_string)
|
|
97
|
+
expected_encoded = self.simple_encode_non_zeros_only(test_string)
|
|
98
|
+
self.assertEqual(encoded, expected_encoded,
|
|
99
|
+
"encoded != expected_encoded for length %d\nencoded: %s\nexpected_encoded: %s" %
|
|
100
|
+
(length, repr(encoded), repr(expected_encoded)))
|
|
101
|
+
|
|
102
|
+
def test_non_zeros_and_trailing_zero(self):
|
|
103
|
+
for length in range(1, 1000):
|
|
104
|
+
non_zeros_string = non_zero_bytes(length)
|
|
105
|
+
test_string = non_zeros_string + b'\x00'
|
|
106
|
+
encoded = cobs.encode(test_string)
|
|
107
|
+
if (len(non_zeros_string) % 254) == 0:
|
|
108
|
+
expected_encoded = self.simple_encode_non_zeros_only(non_zeros_string) + b'\x01\x01'
|
|
109
|
+
else:
|
|
110
|
+
expected_encoded = self.simple_encode_non_zeros_only(non_zeros_string) + b'\x01'
|
|
111
|
+
self.assertEqual(encoded, expected_encoded,
|
|
112
|
+
"encoded != expected_encoded for length %d\nencoded: %s\nexpected_encoded: %s" %
|
|
113
|
+
(length, repr(encoded), repr(expected_encoded)))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class RandomDataTest(unittest.TestCase):
|
|
117
|
+
NUM_TESTS = 5000
|
|
118
|
+
MAX_LENGTH = 2000
|
|
119
|
+
|
|
120
|
+
def test_random(self):
|
|
121
|
+
try:
|
|
122
|
+
for _test_num in range(self.NUM_TESTS):
|
|
123
|
+
length = random.randint(0, self.MAX_LENGTH)
|
|
124
|
+
test_string = bytes(random.randint(0,255) for x in range(length))
|
|
125
|
+
encoded = cobs.encode(test_string)
|
|
126
|
+
self.assertTrue(b'\x00' not in encoded,
|
|
127
|
+
"encoding contains zero byte(s):\noriginal: %s\nencoded: %s" % (repr(test_string), repr(encoded)))
|
|
128
|
+
self.assertTrue(len(encoded) <= len(test_string) + 1 + (len(test_string) // 254),
|
|
129
|
+
"encoding too big:\noriginal: %s\nencoded: %s" % (repr(test_string), repr(encoded)))
|
|
130
|
+
decoded = cobs.decode(encoded)
|
|
131
|
+
self.assertEqual(decoded, test_string,
|
|
132
|
+
"encoding and decoding random data failed:\noriginal: %s\ndecoded: %s" % (repr(test_string), repr(decoded)))
|
|
133
|
+
except KeyboardInterrupt:
|
|
134
|
+
pass
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class InputTypesTest(unittest.TestCase):
|
|
138
|
+
predefined_encodings = [
|
|
139
|
+
[ b"", b"\x01" ],
|
|
140
|
+
[ b"1", b"\x021" ],
|
|
141
|
+
[ b"12345", b"\x0612345" ],
|
|
142
|
+
[ b"12345\x006789", b"\x0612345\x056789" ],
|
|
143
|
+
[ b"\x0012345\x006789", b"\x01\x0612345\x056789" ],
|
|
144
|
+
[ b"12345\x006789\x00", b"\x0612345\x056789\x01" ],
|
|
145
|
+
]
|
|
146
|
+
|
|
147
|
+
def test_unicode_string(self):
|
|
148
|
+
"""Test that Unicode strings are not encoded or decoded.
|
|
149
|
+
They should raise a TypeError."""
|
|
150
|
+
for (test_string, expected_encoded_string) in self.predefined_encodings:
|
|
151
|
+
unicode_test_string = test_string.decode('latin')
|
|
152
|
+
with self.assertRaises(TypeError):
|
|
153
|
+
cobs.encode(unicode_test_string)
|
|
154
|
+
unicode_encoded_string = expected_encoded_string.decode('latin')
|
|
155
|
+
with self.assertRaises(TypeError):
|
|
156
|
+
cobs.decode(unicode_encoded_string)
|
|
157
|
+
|
|
158
|
+
def test_bytearray(self):
|
|
159
|
+
"""Test that bytearray objects can be encoded or decoded."""
|
|
160
|
+
for (test_string, expected_encoded_string) in self.predefined_encodings:
|
|
161
|
+
bytearray_test_string = bytearray(test_string)
|
|
162
|
+
encoded = cobs.encode(bytearray_test_string)
|
|
163
|
+
self.assertEqual(encoded, expected_encoded_string)
|
|
164
|
+
bytearray_encoded_string = bytearray(expected_encoded_string)
|
|
165
|
+
decoded = cobs.decode(bytearray_encoded_string)
|
|
166
|
+
self.assertEqual(decoded, test_string)
|
|
167
|
+
|
|
168
|
+
def test_array_of_bytes(self):
|
|
169
|
+
"""Test that array of bytes objects (array('B', ...)) can be encoded or decoded."""
|
|
170
|
+
for (test_string, expected_encoded_string) in self.predefined_encodings:
|
|
171
|
+
array_test_string = array('B', test_string)
|
|
172
|
+
encoded = cobs.encode(array_test_string)
|
|
173
|
+
self.assertEqual(encoded, expected_encoded_string)
|
|
174
|
+
array_encoded_string = array('B', expected_encoded_string)
|
|
175
|
+
decoded = cobs.decode(array_encoded_string)
|
|
176
|
+
self.assertEqual(decoded, test_string)
|
|
177
|
+
|
|
178
|
+
def test_memoryview(self):
|
|
179
|
+
"""Test that memoryview objects can be encoded or decoded."""
|
|
180
|
+
for (test_string, expected_encoded_string) in self.predefined_encodings:
|
|
181
|
+
encoded = cobs.encode(memoryview(test_string))
|
|
182
|
+
self.assertEqual(encoded, expected_encoded_string)
|
|
183
|
+
decoded = cobs.decode(memoryview(expected_encoded_string))
|
|
184
|
+
self.assertEqual(decoded, test_string)
|
|
185
|
+
|
|
186
|
+
def test_array_of_half_words(self):
|
|
187
|
+
"""Test that array of half-word objects (array('H', ...)) are not encoded or decoded.
|
|
188
|
+
They should raise a BufferError."""
|
|
189
|
+
# Array typecodes for types with size greater than 1.
|
|
190
|
+
# Don't include 'u' for Unicode because it expects a Unicode initialiser.
|
|
191
|
+
typecodes = [ 'H', 'h', 'i', 'I', 'l', 'L', 'f', 'd' ]
|
|
192
|
+
for typecode in typecodes:
|
|
193
|
+
array_test_string = array(typecode, [ 49, 50, 51, 52, 53 ])
|
|
194
|
+
with self.assertRaises(BufferError):
|
|
195
|
+
cobs.encode(array_test_string)
|
|
196
|
+
array_encoded_string = array(typecode, [6, 49, 50, 51, 52, 53 ])
|
|
197
|
+
with self.assertRaises(BufferError):
|
|
198
|
+
cobs.decode(array_encoded_string)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class UtilTests(unittest.TestCase):
|
|
202
|
+
|
|
203
|
+
def test_encoded_len_calc(self):
|
|
204
|
+
self.assertEqual(cobs.encoding_overhead(5), 1)
|
|
205
|
+
self.assertEqual(cobs.max_encoded_length(5), 6)
|
|
206
|
+
|
|
207
|
+
def test_encoded_len_calc_empty_packet(self):
|
|
208
|
+
self.assertEqual(cobs.encoding_overhead(0), 1)
|
|
209
|
+
self.assertEqual(cobs.max_encoded_length(0), 1)
|
|
210
|
+
|
|
211
|
+
def test_encoded_len_calc_still_one_byte_overhead(self):
|
|
212
|
+
self.assertEqual(cobs.encoding_overhead(254), 1)
|
|
213
|
+
self.assertEqual(cobs.max_encoded_length(254), 255)
|
|
214
|
+
|
|
215
|
+
def test_encoded_len_calc_two_byte_overhead(self):
|
|
216
|
+
self.assertEqual(cobs.encoding_overhead(255), 2)
|
|
217
|
+
self.assertEqual(cobs.max_encoded_length(255), 257)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def runtests():
|
|
221
|
+
unittest.main()
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
if __name__ == '__main__':
|
|
225
|
+
runtests()
|
cobs/cobsr/__init__.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Consistent Overhead Byte Stuffing/Reduced (COBS/R) encoding and decoding.
|
|
3
|
+
|
|
4
|
+
Functions are provided for encoding and decoding according to
|
|
5
|
+
the COBS/R method.
|
|
6
|
+
|
|
7
|
+
A pure Python implementation and a C extension implementation
|
|
8
|
+
are provided. If the C extension is not available for some reason,
|
|
9
|
+
the pure Python version will be used.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
from ._cobsr_ext import *
|
|
14
|
+
_using_extension = True
|
|
15
|
+
except ImportError:
|
|
16
|
+
from ._cobsr_py import *
|
|
17
|
+
_using_extension = False
|
|
18
|
+
|
|
19
|
+
DecodeError.__module__ = 'cobs.cobsr'
|
|
20
|
+
|
|
21
|
+
from .._version import *
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def encoding_overhead(source_len):
|
|
25
|
+
"""Calculates the maximum overhead when encoding a message with the given length.
|
|
26
|
+
The overhead is a maximum of [n/254] bytes (one in 254 bytes) rounded up."""
|
|
27
|
+
if source_len == 0:
|
|
28
|
+
return 1
|
|
29
|
+
return (source_len + 253) // 254
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def max_encoded_length(source_len):
|
|
33
|
+
"""Calculates how maximum possible size of an encoded message given the length of the
|
|
34
|
+
source message."""
|
|
35
|
+
return source_len + encoding_overhead(source_len)
|
|
Binary file
|
cobs/cobsr/_cobsr_py.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Consistent Overhead Byte Stuffing/Reduced (COBS/R)
|
|
3
|
+
|
|
4
|
+
This version is for Python 3.x.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class DecodeError(Exception):
|
|
9
|
+
pass
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _get_buffer_view(in_bytes):
|
|
13
|
+
mv = memoryview(in_bytes)
|
|
14
|
+
if mv.ndim > 1 or mv.itemsize > 1:
|
|
15
|
+
raise BufferError('object must be a single-dimension buffer of bytes.')
|
|
16
|
+
try:
|
|
17
|
+
if mv.format != 'B':
|
|
18
|
+
mv = mv.cast('B')
|
|
19
|
+
except AttributeError:
|
|
20
|
+
pass
|
|
21
|
+
return mv
|
|
22
|
+
|
|
23
|
+
def encode(in_bytes):
|
|
24
|
+
"""Encode a string using Consistent Overhead Byte Stuffing/Reduced (COBS/R).
|
|
25
|
+
|
|
26
|
+
Input is any byte string. Output is also a byte string.
|
|
27
|
+
|
|
28
|
+
Encoding guarantees no zero bytes in the output. The output
|
|
29
|
+
string may be expanded slightly, by a predictable amount.
|
|
30
|
+
|
|
31
|
+
An empty string is encoded to '\\x01'"""
|
|
32
|
+
if isinstance(in_bytes, str):
|
|
33
|
+
raise TypeError('Unicode-objects must be encoded as bytes first')
|
|
34
|
+
in_bytes_mv = _get_buffer_view(in_bytes)
|
|
35
|
+
out_bytes = bytearray()
|
|
36
|
+
idx = 0
|
|
37
|
+
search_start_idx = 0
|
|
38
|
+
for in_char in in_bytes_mv:
|
|
39
|
+
if idx - search_start_idx == 0xFE:
|
|
40
|
+
out_bytes.append(0xFF)
|
|
41
|
+
out_bytes += in_bytes_mv[search_start_idx:idx]
|
|
42
|
+
search_start_idx = idx
|
|
43
|
+
if in_char == 0:
|
|
44
|
+
out_bytes.append(idx - search_start_idx + 1)
|
|
45
|
+
out_bytes += in_bytes_mv[search_start_idx:idx]
|
|
46
|
+
search_start_idx = idx + 1
|
|
47
|
+
idx += 1
|
|
48
|
+
try:
|
|
49
|
+
final_byte_value = in_bytes_mv[-1]
|
|
50
|
+
except IndexError:
|
|
51
|
+
final_byte_value = 0
|
|
52
|
+
length_value = idx - search_start_idx + 1
|
|
53
|
+
if final_byte_value < length_value:
|
|
54
|
+
# Encoding same as plain COBS
|
|
55
|
+
out_bytes.append(length_value)
|
|
56
|
+
out_bytes += in_bytes_mv[search_start_idx:idx]
|
|
57
|
+
else:
|
|
58
|
+
# Special COBS/R encoding: length code is final byte,
|
|
59
|
+
# and final byte is removed from data sequence.
|
|
60
|
+
out_bytes.append(final_byte_value)
|
|
61
|
+
out_bytes += in_bytes_mv[search_start_idx:idx - 1]
|
|
62
|
+
return bytes(out_bytes)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def decode(in_bytes):
|
|
66
|
+
"""Decode a string using Consistent Overhead Byte Stuffing/Reduced (COBS/R).
|
|
67
|
+
|
|
68
|
+
Input should be a byte string that has been COBS/R encoded. Output
|
|
69
|
+
is also a byte string.
|
|
70
|
+
|
|
71
|
+
A cobsr.DecodeError exception will be raised if the encoded data
|
|
72
|
+
is invalid. That is, if the encoded data contains zeros."""
|
|
73
|
+
if isinstance(in_bytes, str):
|
|
74
|
+
raise TypeError('Unicode-objects are not supported; byte buffer objects only')
|
|
75
|
+
in_bytes_mv = _get_buffer_view(in_bytes)
|
|
76
|
+
out_bytes = bytearray()
|
|
77
|
+
idx = 0
|
|
78
|
+
|
|
79
|
+
if len(in_bytes_mv) > 0:
|
|
80
|
+
while True:
|
|
81
|
+
length = in_bytes_mv[idx]
|
|
82
|
+
if length == 0:
|
|
83
|
+
raise DecodeError("zero byte found in input")
|
|
84
|
+
idx += 1
|
|
85
|
+
end = idx + length - 1
|
|
86
|
+
copy_mv = in_bytes_mv[idx:end]
|
|
87
|
+
if 0 in copy_mv:
|
|
88
|
+
raise DecodeError("zero byte found in input")
|
|
89
|
+
out_bytes += copy_mv
|
|
90
|
+
idx = end
|
|
91
|
+
if idx > len(in_bytes_mv):
|
|
92
|
+
out_bytes.append(length)
|
|
93
|
+
break
|
|
94
|
+
elif idx < len(in_bytes_mv):
|
|
95
|
+
if length < 0xFF:
|
|
96
|
+
out_bytes.append(0)
|
|
97
|
+
else:
|
|
98
|
+
break
|
|
99
|
+
return bytes(out_bytes)
|
cobs/cobsr/test.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Consistent Overhead Byte Stuffing/Reduced (COBS/R)
|
|
3
|
+
|
|
4
|
+
Unit Tests
|
|
5
|
+
|
|
6
|
+
This version is for Python 3.x.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from array import array
|
|
10
|
+
import random
|
|
11
|
+
import unittest
|
|
12
|
+
|
|
13
|
+
from .. import cobsr as cobsr
|
|
14
|
+
#from ..cobsr import _cobsr_py as cobsr
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def infinite_non_zero_generator():
|
|
18
|
+
while True:
|
|
19
|
+
for i in range(1,50):
|
|
20
|
+
for j in range(1,256, i):
|
|
21
|
+
yield j
|
|
22
|
+
|
|
23
|
+
def non_zero_generator(length):
|
|
24
|
+
non_zeros = infinite_non_zero_generator()
|
|
25
|
+
for i in range(length):
|
|
26
|
+
yield next(non_zeros)
|
|
27
|
+
|
|
28
|
+
def non_zero_bytes(length):
|
|
29
|
+
return b''.join(bytes([i]) for i in non_zero_generator(length))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class PredefinedEncodingsTests(unittest.TestCase):
|
|
33
|
+
predefined_encodings = [
|
|
34
|
+
[ b"", b"\x01" ],
|
|
35
|
+
[ b"\x01", b"\x02\x01" ],
|
|
36
|
+
[ b"\x02", b"\x02" ],
|
|
37
|
+
[ b"\x03", b"\x03" ],
|
|
38
|
+
[ b"\x7E", b"\x7E" ],
|
|
39
|
+
[ b"\x7F", b"\x7F" ],
|
|
40
|
+
[ b"\x80", b"\x80" ],
|
|
41
|
+
[ b"\xD5", b"\xD5" ],
|
|
42
|
+
[ b"\xFE", b"\xFE" ],
|
|
43
|
+
[ b"\xFF", b"\xFF" ],
|
|
44
|
+
[ b"a\x02", b"\x03a\x02" ],
|
|
45
|
+
[ b"a\x03", b"\x03a" ],
|
|
46
|
+
[ b"a\xFF", b"\xFFa" ],
|
|
47
|
+
[ b"\x05\x04\x03\x02\x01", b"\x06\x05\x04\x03\x02\x01" ],
|
|
48
|
+
[ b"12345", b"51234" ],
|
|
49
|
+
[ b"12345\x00\x04\x03\x02\x01", b"\x0612345\x05\x04\x03\x02\x01" ],
|
|
50
|
+
[ b"12345\x006789", b"\x06123459678" ],
|
|
51
|
+
[ b"\x0012345\x006789", b"\x01\x06123459678" ],
|
|
52
|
+
[ b"12345\x006789\x00", b"\x0612345\x056789\x01" ],
|
|
53
|
+
[ b"\x00", b"\x01\x01" ],
|
|
54
|
+
[ b"\x00\x00", b"\x01\x01\x01" ],
|
|
55
|
+
[ b"\x00\x00\x00", b"\x01\x01\x01\x01" ],
|
|
56
|
+
[ bytes(bytearray(range(1, 254))), bytes(b"\xfe" + bytearray(range(1, 254))) ],
|
|
57
|
+
[ bytes(bytearray(range(1, 255))), bytes(b"\xff" + bytearray(range(1, 255))) ],
|
|
58
|
+
[ bytes(bytearray(range(1, 256))), bytes(b"\xff" + bytearray(range(1, 255)) + b"\xff") ],
|
|
59
|
+
[ bytes(bytearray(range(0, 256))), bytes(b"\x01\xff" + bytearray(range(1, 255)) + b"\xff") ],
|
|
60
|
+
[ bytes(bytearray(range(2, 256))), bytes(b"\xff" + bytearray(range(2, 255))) ],
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
def test_predefined_encodings(self):
|
|
64
|
+
for (test_string, expected_encoded_string) in self.predefined_encodings:
|
|
65
|
+
encoded = cobsr.encode(test_string)
|
|
66
|
+
self.assertEqual(encoded, expected_encoded_string)
|
|
67
|
+
|
|
68
|
+
def test_decode_predefined_encodings(self):
|
|
69
|
+
for (test_string, expected_encoded_string) in self.predefined_encodings:
|
|
70
|
+
decoded = cobsr.decode(expected_encoded_string)
|
|
71
|
+
self.assertEqual(test_string, decoded)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class PredefinedDecodeErrorTests(unittest.TestCase):
|
|
75
|
+
decode_error_test_strings = [
|
|
76
|
+
b"\x00",
|
|
77
|
+
b"\x051234\x00",
|
|
78
|
+
b"\x0512\x004",
|
|
79
|
+
]
|
|
80
|
+
|
|
81
|
+
def test_predefined_decode_error(self):
|
|
82
|
+
for test_encoded in self.decode_error_test_strings:
|
|
83
|
+
with self.assertRaises(cobsr.DecodeError):
|
|
84
|
+
cobsr.decode(test_encoded)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class ZerosTest(unittest.TestCase):
|
|
88
|
+
def test_zeros(self):
|
|
89
|
+
for length in range(520):
|
|
90
|
+
test_string = b'\x00' * length
|
|
91
|
+
encoded = cobsr.encode(test_string)
|
|
92
|
+
expected_encoded = b'\x01' * (length + 1)
|
|
93
|
+
self.assertEqual(encoded, expected_encoded, "encoding zeros failed for length %d" % length)
|
|
94
|
+
decoded = cobsr.decode(encoded)
|
|
95
|
+
self.assertEqual(decoded, test_string, "decoding zeros failed for length %d" % length)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class NonZerosTest(unittest.TestCase):
|
|
99
|
+
def simple_encode_non_zeros_only(self, in_bytes):
|
|
100
|
+
out_list = []
|
|
101
|
+
for i in range(0, len(in_bytes), 254):
|
|
102
|
+
data_block = in_bytes[i: i+254]
|
|
103
|
+
out_list.append(bytes([ len(data_block) + 1 ]))
|
|
104
|
+
out_list.append(data_block)
|
|
105
|
+
return b''.join(out_list)
|
|
106
|
+
|
|
107
|
+
def cobsr_encode_final_non_zeros_only(self, in_bytes):
|
|
108
|
+
out_list = []
|
|
109
|
+
for i in range(0, len(in_bytes), 254):
|
|
110
|
+
data_block = in_bytes[i: i+254]
|
|
111
|
+
out_list.append(bytes([ len(data_block) + 1 ]))
|
|
112
|
+
out_list.append(data_block)
|
|
113
|
+
last_block = out_list[-1]
|
|
114
|
+
last_char_value = last_block[-1]
|
|
115
|
+
if last_char_value >= len(last_block) + 1:
|
|
116
|
+
del(out_list[-2:])
|
|
117
|
+
out_list.append(bytes([ last_char_value ]))
|
|
118
|
+
out_list.append(last_block[:-1])
|
|
119
|
+
return b''.join(out_list)
|
|
120
|
+
|
|
121
|
+
def test_non_zeros(self):
|
|
122
|
+
for length in range(1, 1000):
|
|
123
|
+
test_string = non_zero_bytes(length)
|
|
124
|
+
encoded = cobsr.encode(test_string)
|
|
125
|
+
expected_encoded = self.cobsr_encode_final_non_zeros_only(test_string)
|
|
126
|
+
self.assertEqual(encoded, expected_encoded,
|
|
127
|
+
"encoded != expected_encoded for length %d\nencoded: %s\nexpected_encoded: %s" %
|
|
128
|
+
(length, repr(encoded), repr(expected_encoded)))
|
|
129
|
+
|
|
130
|
+
def test_non_zeros_and_trailing_zero(self):
|
|
131
|
+
for length in range(1, 1000):
|
|
132
|
+
non_zeros_string = non_zero_bytes(length)
|
|
133
|
+
test_string = non_zeros_string + b'\x00'
|
|
134
|
+
encoded = cobsr.encode(test_string)
|
|
135
|
+
if (len(non_zeros_string) % 254) == 0:
|
|
136
|
+
expected_encoded = self.simple_encode_non_zeros_only(non_zeros_string) + b'\x01\x01'
|
|
137
|
+
else:
|
|
138
|
+
expected_encoded = self.simple_encode_non_zeros_only(non_zeros_string) + b'\x01'
|
|
139
|
+
self.assertEqual(encoded, expected_encoded,
|
|
140
|
+
"encoded != expected_encoded for length %d\nencoded: %s\nexpected_encoded: %s" %
|
|
141
|
+
(length, repr(encoded), repr(expected_encoded)))
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class RandomDataTest(unittest.TestCase):
|
|
145
|
+
NUM_TESTS = 5000
|
|
146
|
+
MAX_LENGTH = 2000
|
|
147
|
+
|
|
148
|
+
def test_random(self):
|
|
149
|
+
try:
|
|
150
|
+
for _test_num in range(self.NUM_TESTS):
|
|
151
|
+
length = random.randint(0, self.MAX_LENGTH)
|
|
152
|
+
test_string = bytes(random.randint(0,255) for x in range(length))
|
|
153
|
+
encoded = cobsr.encode(test_string)
|
|
154
|
+
self.assertTrue(b'\x00' not in encoded,
|
|
155
|
+
"encoding contains zero byte(s):\noriginal: %s\nencoded: %s" % (repr(test_string), repr(encoded)))
|
|
156
|
+
self.assertTrue(len(encoded) <= len(test_string) + 1 + (len(test_string) // 254),
|
|
157
|
+
"encoding too big:\noriginal: %s\nencoded: %s" % (repr(test_string), repr(encoded)))
|
|
158
|
+
decoded = cobsr.decode(encoded)
|
|
159
|
+
self.assertEqual(decoded, test_string,
|
|
160
|
+
"encoding and decoding random data failed:\noriginal: %s\ndecoded: %s" % (repr(test_string), repr(decoded)))
|
|
161
|
+
except KeyboardInterrupt:
|
|
162
|
+
pass
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class InputTypesTest(unittest.TestCase):
|
|
166
|
+
predefined_encodings = [
|
|
167
|
+
[ b"", b"\x01" ],
|
|
168
|
+
[ b"\x01", b"\x02\x01" ],
|
|
169
|
+
[ b"\x02", b"\x02" ],
|
|
170
|
+
[ b"\x7F", b"\x7F" ],
|
|
171
|
+
[ b"\x80", b"\x80" ],
|
|
172
|
+
[ b"\xD5", b"\xD5" ],
|
|
173
|
+
[ b"1", b"1" ],
|
|
174
|
+
[ b"\x05\x04\x03\x02\x01", b"\x06\x05\x04\x03\x02\x01" ],
|
|
175
|
+
[ b"12345", b"51234" ],
|
|
176
|
+
[ b"12345\x00\x04\x03\x02\x01", b"\x0612345\x05\x04\x03\x02\x01" ],
|
|
177
|
+
[ b"12345\x006789", b"\x06123459678" ],
|
|
178
|
+
]
|
|
179
|
+
|
|
180
|
+
def test_unicode_string(self):
|
|
181
|
+
"""Test that Unicode strings are not encoded or decoded.
|
|
182
|
+
They should raise a TypeError."""
|
|
183
|
+
for (test_string, expected_encoded_string) in self.predefined_encodings:
|
|
184
|
+
unicode_test_string = test_string.decode('latin')
|
|
185
|
+
with self.assertRaises(TypeError):
|
|
186
|
+
cobsr.encode(unicode_test_string)
|
|
187
|
+
unicode_encoded_string = expected_encoded_string.decode('latin')
|
|
188
|
+
with self.assertRaises(TypeError):
|
|
189
|
+
cobsr.decode(unicode_encoded_string)
|
|
190
|
+
|
|
191
|
+
def test_bytearray(self):
|
|
192
|
+
"""Test that bytearray objects can be encoded or decoded."""
|
|
193
|
+
for (test_string, expected_encoded_string) in self.predefined_encodings:
|
|
194
|
+
bytearray_test_string = bytearray(test_string)
|
|
195
|
+
encoded = cobsr.encode(bytearray_test_string)
|
|
196
|
+
self.assertEqual(encoded, expected_encoded_string)
|
|
197
|
+
bytearray_encoded_string = bytearray(expected_encoded_string)
|
|
198
|
+
decoded = cobsr.decode(bytearray_encoded_string)
|
|
199
|
+
self.assertEqual(decoded, test_string)
|
|
200
|
+
|
|
201
|
+
def test_array_of_bytes(self):
|
|
202
|
+
"""Test that array of bytes objects (array('B', ...)) can be encoded or decoded."""
|
|
203
|
+
for (test_string, expected_encoded_string) in self.predefined_encodings:
|
|
204
|
+
array_test_string = array('B', test_string)
|
|
205
|
+
encoded = cobsr.encode(array_test_string)
|
|
206
|
+
self.assertEqual(encoded, expected_encoded_string)
|
|
207
|
+
array_encoded_string = array('B', expected_encoded_string)
|
|
208
|
+
decoded = cobsr.decode(array_encoded_string)
|
|
209
|
+
self.assertEqual(decoded, test_string)
|
|
210
|
+
|
|
211
|
+
def test_memoryview(self):
|
|
212
|
+
"""Test that memoryview objects can be encoded or decoded."""
|
|
213
|
+
for (test_string, expected_encoded_string) in self.predefined_encodings:
|
|
214
|
+
encoded = cobsr.encode(memoryview(test_string))
|
|
215
|
+
self.assertEqual(encoded, expected_encoded_string)
|
|
216
|
+
decoded = cobsr.decode(memoryview(expected_encoded_string))
|
|
217
|
+
self.assertEqual(decoded, test_string)
|
|
218
|
+
|
|
219
|
+
def test_array_of_half_words(self):
|
|
220
|
+
"""Test that array of half-word objects (array('H', ...)) are not encoded or decoded.
|
|
221
|
+
They should raise a BufferError."""
|
|
222
|
+
# Array typecodes for types with size greater than 1.
|
|
223
|
+
# Don't include 'u' for Unicode because it expects a Unicode initialiser.
|
|
224
|
+
typecodes = [ 'H', 'h', 'i', 'I', 'l', 'L', 'f', 'd' ]
|
|
225
|
+
for typecode in typecodes:
|
|
226
|
+
array_test_string = array(typecode, [ 49, 50, 51, 52, 53 ])
|
|
227
|
+
with self.assertRaises(BufferError):
|
|
228
|
+
cobsr.encode(array_test_string)
|
|
229
|
+
array_encoded_string = array(typecode, [6, 49, 50, 51, 52, 53 ])
|
|
230
|
+
with self.assertRaises(BufferError):
|
|
231
|
+
cobsr.decode(array_encoded_string)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
class UtilTests(unittest.TestCase):
|
|
235
|
+
|
|
236
|
+
def test_encoded_len_calc(self):
|
|
237
|
+
self.assertEqual(cobsr.encoding_overhead(5), 1)
|
|
238
|
+
self.assertEqual(cobsr.max_encoded_length(5), 6)
|
|
239
|
+
|
|
240
|
+
def test_encoded_len_calc_empty_packet(self):
|
|
241
|
+
self.assertEqual(cobsr.encoding_overhead(0), 1)
|
|
242
|
+
self.assertEqual(cobsr.max_encoded_length(0), 1)
|
|
243
|
+
|
|
244
|
+
def test_encoded_len_calc_still_one_byte_overhead(self):
|
|
245
|
+
self.assertEqual(cobsr.encoding_overhead(254), 1)
|
|
246
|
+
self.assertEqual(cobsr.max_encoded_length(254), 255)
|
|
247
|
+
|
|
248
|
+
def test_encoded_len_calc_two_byte_overhead(self):
|
|
249
|
+
self.assertEqual(cobsr.encoding_overhead(255), 2)
|
|
250
|
+
self.assertEqual(cobsr.max_encoded_length(255), 257)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def runtests():
|
|
254
|
+
unittest.main()
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
if __name__ == '__main__':
|
|
258
|
+
runtests()
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cobs
|
|
3
|
+
Version: 1.2.3
|
|
4
|
+
Summary: Consistent Overhead Byte Stuffing (COBS)
|
|
5
|
+
Author-email: Craig McQueen <python@craig.mcqueen.id.au>
|
|
6
|
+
License: ----------------------------------------------------------------------------
|
|
7
|
+
Copyright (c) 2010 Craig McQueen
|
|
8
|
+
|
|
9
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
10
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
11
|
+
in the Software without restriction, including without limitation the rights
|
|
12
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
13
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
14
|
+
furnished to do so, subject to the following conditions:
|
|
15
|
+
|
|
16
|
+
The above copyright notice and this permission notice shall be included in
|
|
17
|
+
all copies or substantial portions of the Software.
|
|
18
|
+
|
|
19
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
20
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
21
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
22
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
23
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
24
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
25
|
+
SOFTWARE.
|
|
26
|
+
----------------------------------------------------------------------------
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
Project-URL: Homepage, https://github.com/cmcqueen/cobs-python
|
|
30
|
+
Project-URL: Bug Tracker, https://github.com/cmcqueen/cobs-python/issues
|
|
31
|
+
Keywords: byte stuffing
|
|
32
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
33
|
+
Classifier: Intended Audience :: Developers
|
|
34
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
35
|
+
Classifier: Programming Language :: Python :: 3
|
|
36
|
+
Classifier: Topic :: Communications
|
|
37
|
+
Requires-Python: >=3.6
|
|
38
|
+
Description-Content-Type: text/x-rst
|
|
39
|
+
License-File: LICENSE.txt
|
|
40
|
+
Dynamic: license-file
|
|
41
|
+
|
|
42
|
+
========================================
|
|
43
|
+
Consistent Overhead Byte Stuffing (COBS)
|
|
44
|
+
========================================
|
|
45
|
+
|
|
46
|
+
:Author: Craig McQueen
|
|
47
|
+
:Contact: http://craig.mcqueen.id.au/
|
|
48
|
+
:Copyright: 2010 Craig McQueen
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
Python functions for encoding and decoding COBS.
|
|
52
|
+
|
|
53
|
+
-----
|
|
54
|
+
Intro
|
|
55
|
+
-----
|
|
56
|
+
|
|
57
|
+
The ``cobs`` package is provided, which contains modules containing functions
|
|
58
|
+
for encoding and decoding according to COBS methods.
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
What Is COBS?
|
|
62
|
+
`````````````
|
|
63
|
+
|
|
64
|
+
COBS is a method of encoding a packet of bytes into a form that contains no
|
|
65
|
+
bytes with value zero (0x00). The input packet of bytes can contain bytes
|
|
66
|
+
in the full range of 0x00 to 0xFF. The COBS encoded packet is guaranteed to
|
|
67
|
+
generate packets with bytes only in the range 0x01 to 0xFF. Thus, in a
|
|
68
|
+
communication protocol, packet boundaries can be reliably delimited with 0x00
|
|
69
|
+
bytes.
|
|
70
|
+
|
|
71
|
+
The COBS encoding does have to increase the packet size to achieve this
|
|
72
|
+
encoding. However, compared to other byte-stuffing methods, the packet size
|
|
73
|
+
increase is reasonable and predictable. COBS always adds 1 byte to the
|
|
74
|
+
message length. Additionally, for longer packets of length *n*, it *may* add
|
|
75
|
+
n/254 (rounded down) additional bytes to the encoded packet size.
|
|
76
|
+
|
|
77
|
+
For example, compare to the PPP protocol, which uses 0x7E bytes to delimit
|
|
78
|
+
PPP packets. The PPP protocol uses an "escape" style of byte stuffing,
|
|
79
|
+
replacing all occurences of 0x7E bytes in the packet with 0x7D 0x5E. But that
|
|
80
|
+
byte-stuffing method can potentially double the size of the packet in the
|
|
81
|
+
worst case. COBS uses a different method for byte-stuffing, which has a much
|
|
82
|
+
more reasonable worst-case overhead.
|
|
83
|
+
|
|
84
|
+
For more details about COBS, see the references [#ieeeton]_ [#ppp]_.
|
|
85
|
+
|
|
86
|
+
I have included a variant on COBS, `COBS/R`_, which slightly modifies COBS to
|
|
87
|
+
often avoid the +1 byte overhead of COBS. So in many cases, especially for
|
|
88
|
+
smaller packets, the size of a COBS/R encoded packet is the same size as the
|
|
89
|
+
original packet. See below for more details about `COBS/R`_.
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
References
|
|
93
|
+
``````````
|
|
94
|
+
|
|
95
|
+
.. [#ieeeton] | `Consistent Overhead Byte Stuffing`__
|
|
96
|
+
| Stuart Cheshire and Mary Baker
|
|
97
|
+
| IEEE/ACM Transations on Networking, Vol. 7, No. 2, April 1999
|
|
98
|
+
|
|
99
|
+
.. __:
|
|
100
|
+
.. _Consistent Overhead Byte Stuffing (for IEEE):
|
|
101
|
+
http://www.stuartcheshire.org/papers/COBSforToN.pdf
|
|
102
|
+
|
|
103
|
+
.. [#ppp] | `PPP Consistent Overhead Byte Stuffing (COBS)`_
|
|
104
|
+
| PPP Working Group Internet Draft
|
|
105
|
+
| James Carlson, IronBridge Networks
|
|
106
|
+
| Stuart Cheshire and Mary Baker, Stanford University
|
|
107
|
+
| November 1997
|
|
108
|
+
|
|
109
|
+
.. _PPP Consistent Overhead Byte Stuffing (COBS):
|
|
110
|
+
http://tools.ietf.org/html/draft-ietf-pppext-cobs-00
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
----------------
|
|
114
|
+
Modules Provided
|
|
115
|
+
----------------
|
|
116
|
+
|
|
117
|
+
================== ================== ===============================================================
|
|
118
|
+
Module Short Name Long Name
|
|
119
|
+
================== ================== ===============================================================
|
|
120
|
+
``cobs.cobs`` COBS Consistent Overhead Byte Stuffing (basic method) [#ieeeton]_
|
|
121
|
+
``cobs.cobsr`` `COBS/R`_ `Consistent Overhead Byte Stuffing--Reduced`_
|
|
122
|
+
================== ================== ===============================================================
|
|
123
|
+
|
|
124
|
+
"`Consistent Overhead Byte Stuffing--Reduced`_" (`COBS/R`_) is my own invention,
|
|
125
|
+
a modification of basic COBS encoding, and is described in more detail below.
|
|
126
|
+
|
|
127
|
+
The following are not implemented:
|
|
128
|
+
|
|
129
|
+
================== ======================================================================
|
|
130
|
+
Short Name Long Name
|
|
131
|
+
================== ======================================================================
|
|
132
|
+
COBS/ZPE Consistent Overhead Byte Stuffing--Zero Pair Elimination [#ieeeton]_
|
|
133
|
+
COBS/ZRE Consistent Overhead Byte Stuffing--Zero Run Elimination [#ppp]_
|
|
134
|
+
================== ======================================================================
|
|
135
|
+
|
|
136
|
+
A pure Python implementation and a C extension implementation are provided. If
|
|
137
|
+
the C extension is not available for some reason, the pure Python version will
|
|
138
|
+
be used.
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
-----
|
|
142
|
+
Usage
|
|
143
|
+
-----
|
|
144
|
+
|
|
145
|
+
The modules provide an ``encode`` and a ``decode`` function.
|
|
146
|
+
|
|
147
|
+
The input should be a byte string, not a Unicode string. Basic usage::
|
|
148
|
+
|
|
149
|
+
>>> from cobs import cobs
|
|
150
|
+
>>> encoded = cobs.encode(b'Hello world\x00This is a test')
|
|
151
|
+
>>> encoded
|
|
152
|
+
b'\x0cHello world\x0fThis is a test'
|
|
153
|
+
>>> cobs.decode(encoded)
|
|
154
|
+
b'Hello world\x00This is a test'
|
|
155
|
+
|
|
156
|
+
`COBS/R`_ usage is almost identical::
|
|
157
|
+
|
|
158
|
+
>>> from cobs import cobsr
|
|
159
|
+
>>> encoded = cobsr.encode(b'Hello world\x00This is a test')
|
|
160
|
+
>>> encoded
|
|
161
|
+
b'\x0cHello worldtThis is a tes'
|
|
162
|
+
>>> cobsr.decode(encoded)
|
|
163
|
+
b'Hello world\x00This is a test'
|
|
164
|
+
|
|
165
|
+
Any type that implements the buffer protocol, providing a single block of
|
|
166
|
+
bytes, is also acceptable as input::
|
|
167
|
+
|
|
168
|
+
>>> from cobs import cobs
|
|
169
|
+
>>> encoded = cobs.encode(bytearray(b'Hello world\x00This is a test'))
|
|
170
|
+
>>> encoded
|
|
171
|
+
b'\x0cHello world\x0fThis is a test'
|
|
172
|
+
>>> cobs.decode(encoded)
|
|
173
|
+
b'Hello world\x00This is a test'
|
|
174
|
+
|
|
175
|
+
Note that the ``encode`` function does not add any framing ``0x00`` byte at
|
|
176
|
+
the end (or beginning) of the encoded data. Similarly, the ``decode`` function
|
|
177
|
+
does not strip or split on any framing ``0x00`` bytes, but treats any ``0x00``
|
|
178
|
+
bytes as a data input error. The details of data framing is
|
|
179
|
+
application-specific, so it is the user's application's responsibility to
|
|
180
|
+
implement the framing and deframing that is suitable for the needs of the
|
|
181
|
+
application.
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
-------------------------
|
|
185
|
+
Supported Python Versions
|
|
186
|
+
-------------------------
|
|
187
|
+
|
|
188
|
+
Python >= 3.10 are supported, and have both a C extension and a pure Python
|
|
189
|
+
implementation.
|
|
190
|
+
|
|
191
|
+
Python versions < 3.10 might work, but have not been tested.
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
------------
|
|
195
|
+
Installation
|
|
196
|
+
------------
|
|
197
|
+
|
|
198
|
+
The cobs package is installed using ``distutils``. If you have the tools
|
|
199
|
+
installed to build a Python extension module, run the following command::
|
|
200
|
+
|
|
201
|
+
python setup.py install
|
|
202
|
+
|
|
203
|
+
If you cannot build the C extension, you may install just the pure Python
|
|
204
|
+
implementation, using the following command::
|
|
205
|
+
|
|
206
|
+
python setup.py build_py install --skip-build
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
------------
|
|
210
|
+
Unit Testing
|
|
211
|
+
------------
|
|
212
|
+
|
|
213
|
+
Basic unit testing is in the ``test`` sub-module, e.g. ``cobs.cobs.test``. To run it::
|
|
214
|
+
|
|
215
|
+
python -m cobs.cobs.test
|
|
216
|
+
python -m cobs.cobsr.test
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
-------------
|
|
220
|
+
Documentation
|
|
221
|
+
-------------
|
|
222
|
+
|
|
223
|
+
Documentation is written with Sphinx. Source files are provided in the ``doc``
|
|
224
|
+
directory. It can be built using Sphinx 0.6.5. It uses the ``pngmath`` Sphinx
|
|
225
|
+
extension, which requires Latex and ``dvipng`` to be installed.
|
|
226
|
+
|
|
227
|
+
The documentation is available online at: http://packages.python.org/cobs/
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
-------
|
|
231
|
+
License
|
|
232
|
+
-------
|
|
233
|
+
|
|
234
|
+
The code is released under the MIT license. See LICENSE.txt for details.
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
.. _COBS/R:
|
|
238
|
+
.. _Consistent Overhead Byte Stuffing--Reduced:
|
|
239
|
+
|
|
240
|
+
---------------------------------------------------
|
|
241
|
+
Consistent Overhead Byte Stuffing--Reduced (COBS/R)
|
|
242
|
+
---------------------------------------------------
|
|
243
|
+
|
|
244
|
+
A modification of COBS, which I'm calling "Consistent Overhead Byte
|
|
245
|
+
Stuffing--Reduced" (COBS/R), is provided in the ``cobs.cobsr`` module. Its
|
|
246
|
+
purpose is to save one byte from the encoded form in some cases. Plain COBS
|
|
247
|
+
encoding always has a +1 byte encoding overhead. See the references for
|
|
248
|
+
details [#ieeeton]_. COBS/R can often avoid the +1 byte, which can be a useful
|
|
249
|
+
savings if it is mostly small messages that are being encoded.
|
|
250
|
+
|
|
251
|
+
In plain COBS, the last length code byte in the message has some inherent
|
|
252
|
+
redundancy: if it is greater than the number of remaining bytes, this is
|
|
253
|
+
detected as an error.
|
|
254
|
+
|
|
255
|
+
In COBS/R, instead we opportunistically replace the final length code byte with
|
|
256
|
+
the final data byte, whenever the value of the final data byte is greater than
|
|
257
|
+
or equal to what the final length value would normally be. This variation can be
|
|
258
|
+
unambiguously decoded: the decoder notices that the length code is greater than
|
|
259
|
+
the number of remaining bytes.
|
|
260
|
+
|
|
261
|
+
Examples
|
|
262
|
+
````````
|
|
263
|
+
|
|
264
|
+
The byte values in the examples are in hex.
|
|
265
|
+
|
|
266
|
+
First example:
|
|
267
|
+
|
|
268
|
+
Input:
|
|
269
|
+
|
|
270
|
+
====== ====== ====== ====== ====== ======
|
|
271
|
+
2F A2 00 92 73 02
|
|
272
|
+
====== ====== ====== ====== ====== ======
|
|
273
|
+
|
|
274
|
+
This example is encoded the same in COBS and COBS/R. Encoded (length code bytes
|
|
275
|
+
are bold):
|
|
276
|
+
|
|
277
|
+
====== ====== ====== ====== ====== ====== ======
|
|
278
|
+
**03** 2F A2 **04** 92 73 02
|
|
279
|
+
====== ====== ====== ====== ====== ====== ======
|
|
280
|
+
|
|
281
|
+
Second example:
|
|
282
|
+
|
|
283
|
+
The second example is almost the same, except the final data byte value is
|
|
284
|
+
greater than what the length byte would be.
|
|
285
|
+
|
|
286
|
+
Input:
|
|
287
|
+
|
|
288
|
+
====== ====== ====== ====== ====== ======
|
|
289
|
+
2F A2 00 92 73 26
|
|
290
|
+
====== ====== ====== ====== ====== ======
|
|
291
|
+
|
|
292
|
+
Encoded in plain COBS (length code bytes are bold):
|
|
293
|
+
|
|
294
|
+
====== ====== ====== ====== ====== ====== ======
|
|
295
|
+
**03** 2F A2 **04** 92 73 26
|
|
296
|
+
====== ====== ====== ====== ====== ====== ======
|
|
297
|
+
|
|
298
|
+
Encoded in COBS/R:
|
|
299
|
+
|
|
300
|
+
====== ====== ====== ====== ====== ======
|
|
301
|
+
**03** 2F A2 **26** 92 73
|
|
302
|
+
====== ====== ====== ====== ====== ======
|
|
303
|
+
|
|
304
|
+
Because the last data byte (**26**) is greater than the usual length code
|
|
305
|
+
(**04**), the last data byte can be inserted in place of the length code, and
|
|
306
|
+
removed from the end of the sequence. This avoids the usual +1 byte overhead of
|
|
307
|
+
the COBS encoding.
|
|
308
|
+
|
|
309
|
+
The decoder detects this variation on the encoding simply by detecting that the
|
|
310
|
+
length code is greater than the number of remaining bytes. That situation would
|
|
311
|
+
be a decoding error in regular COBS, but in COBS/R it is used to save one byte
|
|
312
|
+
in the encoded message.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
cobs/__init__.py,sha256=dFPqtW7BAgG7vlfoDbnBFPuMvRHmPhNaGv14m6ZGyLQ,347
|
|
2
|
+
cobs/_version/__init__.py,sha256=ohE2GZqeYOq1sQyh6BagtnlPH0GZTRWCCqHJgJzb1zQ,330
|
|
3
|
+
cobs/cobs/__init__.py,sha256=tPX_7lVZZ5ct1iDmsTLL_eEGK8ZUHkfqlJCXWnu0MU4,1211
|
|
4
|
+
cobs/cobs/_cobs_ext.cp315-win_amd64.pyd,sha256=jxqhHAZKHLbnig2iUJWH5ZNg3txLRG3M3-QuBkDSYbM,14336
|
|
5
|
+
cobs/cobs/_cobs_py.py,sha256=K_meuYatS_Ov8zToCPacSrWinIarVfTMJRzHSYijbzk,2906
|
|
6
|
+
cobs/cobs/test.py,sha256=cCUxUgLL7DRzOt_s5iR_geO-sOSST7lIWVs7Awd2dVA,10574
|
|
7
|
+
cobs/cobsr/__init__.py,sha256=wjRUTz1pgxiCxeBtvevHuxtlIKlMBKZjT_V8Nr-SS7A,1026
|
|
8
|
+
cobs/cobsr/_cobsr_ext.cp315-win_amd64.pyd,sha256=cFg65Yv06JAtetnnASIAzXKAH_0qHuOVXk04r47U2no,14336
|
|
9
|
+
cobs/cobsr/_cobsr_py.py,sha256=8TRm8Aeqd6o76MsuIurMrLG3A6o7kkZjM6J0wQ7OwLo,3247
|
|
10
|
+
cobs/cobsr/test.py,sha256=ExUHj0lNR8B7AFSnObczQPuZFJIwKkcHruiY9m9Jufg,13353
|
|
11
|
+
cobs-1.2.3.dist-info/licenses/LICENSE.txt,sha256=1MRgyU9qqKN6L3MsqVkGeJkWojtwYbBqV3TQ2McCvFM,1212
|
|
12
|
+
cobs-1.2.3.dist-info/METADATA,sha256=zXKV3ntWPWclW7iq6QpyCdIO-ihJ5t-PO4wDxCthZDw,12002
|
|
13
|
+
cobs-1.2.3.dist-info/WHEEL,sha256=0gLwYZa0C2fhgCxWR2c8HahwUiopqonVCV0wVwEg6fE,101
|
|
14
|
+
cobs-1.2.3.dist-info/top_level.txt,sha256=f2FGUEVXVdxrGiCk9EFouAvhepW4NNmvpCcEuJf-o9g,5
|
|
15
|
+
cobs-1.2.3.dist-info/RECORD,,
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
----------------------------------------------------------------------------
|
|
2
|
+
Copyright (c) 2010 Craig McQueen
|
|
3
|
+
|
|
4
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
in the Software without restriction, including without limitation the rights
|
|
7
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
9
|
+
furnished to do so, subject to the following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice shall be included in
|
|
12
|
+
all copies or substantial portions of the Software.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
15
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
16
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
17
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
18
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
19
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
20
|
+
SOFTWARE.
|
|
21
|
+
----------------------------------------------------------------------------
|
|
22
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cobs
|