|
| 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