Skip to content

Commit 59b2f0f

Browse files
committed
add two new functions
- `encoding_overhead` for a given source length - `max_encoded_length` for a given source length - Unittests for both functions
1 parent 8a26e66 commit 59b2f0f

2 files changed

Lines changed: 30 additions & 1 deletion

File tree

python3/cobs/cobs/__init__.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,14 @@
2727

2828
from .._version import *
2929

30+
31+
def encoding_overhead(source_len: int) -> int:
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+
return (source_len + 254 - 1) // 254
35+
36+
37+
def max_encoded_length(source_len: int) -> int:
38+
"""Calculates how maximum possible size of an encoded message given the length of the
39+
source message."""
40+
return source_len + encoding_overhead(source_len)

python3/cobs/cobs/test.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
from .. import cobs as cobs
1414
#from ..cobs import _cobs_py as cobs
1515

16-
1716
def infinite_non_zero_generator():
1817
while True:
1918
for i in range(1,50):
@@ -191,6 +190,25 @@ def test_array_of_half_words(self):
191190
cobs.decode(array_encoded_string)
192191

193192

193+
class UtilTests(unittest.TestCase):
194+
195+
def test_encoded_len_calc(self):
196+
self.assertEqual(cobs.encoding_overhead(5), 1)
197+
self.assertEqual(cobs.max_encoded_length(5), 6)
198+
199+
def test_encoded_len_calc_empty_packet(self):
200+
self.assertEqual(cobs.encoding_overhead(0), 0)
201+
self.assertEqual(cobs.max_encoded_length(0), 0)
202+
203+
def test_encoded_len_calc_still_one_byte_overhead(self):
204+
self.assertEqual(cobs.encoding_overhead(254), 1)
205+
self.assertEqual(cobs.max_encoded_length(254), 255)
206+
207+
def test_encoded_len_calc_two_byte_overhead(self):
208+
self.assertEqual(cobs.encoding_overhead(255), 2)
209+
self.assertEqual(cobs.max_encoded_length(255), 257)
210+
211+
194212
def runtests():
195213
unittest.main()
196214

0 commit comments

Comments
 (0)