Skip to content

Commit

Permalink
cobs_encode_max (#11)
Browse files Browse the repository at this point in the history
  • Loading branch information
charlesnicholson authored Apr 23, 2021
1 parent e5fb211 commit df31c7b
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 1 deletion.
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
SRCS := cobs.c \
tests/test_cobs_encode_max.cc \
tests/test_cobs_encode.cc \
tests/test_cobs_encode_inplace.cc \
tests/test_cobs_decode_inplace.cc \
Expand Down
4 changes: 4 additions & 0 deletions cobs.c
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ cobs_ret_t cobs_decode_inplace(void *buf, unsigned len) {
return COBS_RET_SUCCESS;
}

unsigned cobs_encode_max(unsigned dec_len) {
return 1 + dec_len + ((dec_len + 253) / 254) + (dec_len == 0);
}

cobs_ret_t cobs_encode(void const *dec,
unsigned dec_len,
void *out_enc,
Expand Down
2 changes: 2 additions & 0 deletions cobs.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ extern "C" {
cobs_ret_t cobs_encode_inplace(void *buf, unsigned len);
cobs_ret_t cobs_decode_inplace(void *buf, unsigned len);

unsigned cobs_encode_max(unsigned dec_len);

cobs_ret_t cobs_encode(void const *dec,
unsigned dec_len,
void *out_enc,
Expand Down
15 changes: 14 additions & 1 deletion tests/test_cobs_encode.cc
Original file line number Diff line number Diff line change
Expand Up @@ -110,5 +110,18 @@ TEST_CASE("Simple encodings", "[cobs_encode]") {
}
}

TEST_CASE("0xFE and 0xFF single code-block cases", "[cobs_encode]") {
TEST_CASE("0xFF single code-block case", "[cobs_encode]") {
byte_vec_t dec(254, 0x01);
byte_vec_t enc( cobs_encode_max(static_cast< unsigned >(dec.size())) );
unsigned enc_len;
REQUIRE( cobs_encode(dec.data(),
static_cast< unsigned >(dec.size()),
enc.data(),
static_cast< unsigned >(enc.size()),
&enc_len) == COBS_RET_SUCCESS );

byte_vec_t expected(255, 0x01);
expected[0] = 0xFF;
expected.push_back(0x00);
REQUIRE ( enc == expected );
}
22 changes: 22 additions & 0 deletions tests/test_cobs_encode_max.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#include "../cobs.h"
#include "catch.hpp"

TEST_CASE("cobs_encode_max", "[cobs_encode_max]") {
SECTION("0 bytes") { REQUIRE( cobs_encode_max(0) == 2 ); }
SECTION("1 byte") { REQUIRE( cobs_encode_max(1) == 3 ); }
SECTION("2 bytes") { REQUIRE( cobs_encode_max(2) == 4 ); }

SECTION("3 - 254 bytes") {
for (auto i = 3u; i <= 254u; ++i) {
REQUIRE( cobs_encode_max(i) == i + 2 );
}
}

SECTION("255-508 bytes") {
for (auto i = 255u; i <= 508u; ++i) { REQUIRE( cobs_encode_max(i) == i + 3 ); }
}

SECTION("Input size plus boilerplate plus ceil(x/254)") {
REQUIRE( cobs_encode_max(12345) == 1 + 12345 + ((12345 + 253) / 254) );
}
}

0 comments on commit df31c7b

Please sign in to comment.