Skip to content

Commit ecee66d

Browse files
committed
hex: add tests
1 parent 9a83a85 commit ecee66d

File tree

2 files changed

+55
-1
lines changed

2 files changed

+55
-1
lines changed

extras/test/CMakeLists.txt

+2-1
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,14 @@ set(TEST_SRCS
2626
src/crc32/test_crc32.cpp
2727
src/crc16/test_crc16.cpp
2828
src/sha256/test_sha256.cpp
29+
src/hex/test_hex.cpp
2930
)
3031

3132
set(TEST_DUT_SRCS
3233
../../src/crc/crc32.cpp
3334
../../src/crc/crc16.cpp
34-
../../src/sha256/SHA256.cpp
3535
../../src/sha256/sha2.c
36+
../../src/hex/chex.h
3637
)
3738

3839
##########################################################################

extras/test/src/hex/test_hex.cpp

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
This file is part of the Arduino_CloudUtils library.
3+
4+
Copyright (c) 2024 Arduino SA
5+
6+
This Source Code Form is subject to the terms of the Mozilla Public
7+
License, v. 2.0. If a copy of the MPL was not distributed with this
8+
file, You can obtain one at http://mozilla.org/MPL/2.0/.
9+
*/
10+
11+
#include <catch2/catch_test_macros.hpp>
12+
13+
#include <hex/chex.h>
14+
15+
SCENARIO( "HEX encoding test" ) {
16+
/* check all possible 16-bit values in network byte order */
17+
unsigned i;
18+
for(i = 0; i <= 0xffff; ++i){
19+
/* encode to hex string using our implementation */
20+
const unsigned char org[2] = {(unsigned char)(i>>8), (unsigned char)i};
21+
char hex[5];
22+
chex_encode(hex, sizeof(hex), org, sizeof(org));
23+
24+
/* decode from hex string using a function from the standard library */
25+
unsigned char bin[2];
26+
int n = sscanf(hex, "%02hhx%02hhx", bin, bin+1);
27+
REQUIRE(n == sizeof(bin));
28+
29+
/* decoded matches the original */
30+
REQUIRE(memcmp(org, bin, sizeof(bin)) == 0);
31+
}
32+
REQUIRE(i == 0x10000);
33+
}
34+
35+
SCENARIO( "HEX decoding test" ) {
36+
/* check all possible 16-bit values in network byte order */
37+
unsigned i;
38+
for(i = 0; i <= 0xffff; ++i){
39+
/* encode to hex string using a function from the standard library */
40+
char hex[5];
41+
snprintf(hex, sizeof(hex), "%02hhX%02hhx", (unsigned char)(i>>8), (unsigned char)i);
42+
43+
/* decode from hex string using our implementation */
44+
unsigned char bin[2];
45+
unsigned n = chex_decode(bin, sizeof(bin), hex, sizeof(hex));
46+
REQUIRE(n == sizeof(bin));
47+
48+
/* decoded matches the original */
49+
const unsigned char org[2] = {(unsigned char)(i>>8), (unsigned char)i};
50+
REQUIRE(memcmp(org, bin, sizeof(bin)) == 0);
51+
}
52+
REQUIRE(i == 0x10000);
53+
}

0 commit comments

Comments
 (0)