Fix str_hex and add tests

- Properly null-terminate the destination buffer when the data size is zero.
- Fix early loop exit when destination buffer is too small for all data.
This commit is contained in:
Robert Müller 2022-09-29 16:18:35 +02:00
parent 3383b7dc0f
commit 9472db419b
2 changed files with 40 additions and 7 deletions

View file

@ -3041,15 +3041,16 @@ int str_countchr(const char *haystack, char needle)
void str_hex(char *dst, int dst_size, const void *data, int data_size) void str_hex(char *dst, int dst_size, const void *data, int data_size)
{ {
static const char hex[] = "0123456789ABCDEF"; static const char hex[] = "0123456789ABCDEF";
int b; int data_index;
int dst_index;
for(b = 0; b < data_size && b < dst_size / 4 - 4; b++) for(data_index = 0, dst_index = 0; data_index < data_size && dst_index < dst_size - 3; data_index++)
{ {
dst[b * 3] = hex[((const unsigned char *)data)[b] >> 4]; dst[data_index * 3] = hex[((const unsigned char *)data)[data_index] >> 4];
dst[b * 3 + 1] = hex[((const unsigned char *)data)[b] & 0xf]; dst[data_index * 3 + 1] = hex[((const unsigned char *)data)[data_index] & 0xf];
dst[b * 3 + 2] = ' '; dst[data_index * 3 + 2] = ' ';
dst[b * 3 + 3] = 0; dst_index += 3;
} }
dst[dst_index] = '\0';
} }
static int hexval(char x) static int hexval(char x)

View file

@ -200,6 +200,38 @@ TEST(Str, EndswithNocase)
str_length(ABCDEFG) - str_length(DEFG)); str_length(ABCDEFG) - str_length(DEFG));
} }
TEST(Str, HexEncode)
{
char aOut[64];
const char *pData = "ABCD";
str_hex(aOut, sizeof(aOut), pData, 0);
EXPECT_STREQ(aOut, "");
str_hex(aOut, sizeof(aOut), pData, 1);
EXPECT_STREQ(aOut, "41 ");
str_hex(aOut, sizeof(aOut), pData, 2);
EXPECT_STREQ(aOut, "41 42 ");
str_hex(aOut, sizeof(aOut), pData, 3);
EXPECT_STREQ(aOut, "41 42 43 ");
str_hex(aOut, sizeof(aOut), pData, 4);
EXPECT_STREQ(aOut, "41 42 43 44 ");
str_hex(aOut, 1, pData, 4);
EXPECT_STREQ(aOut, "");
str_hex(aOut, 2, pData, 4);
EXPECT_STREQ(aOut, "");
str_hex(aOut, 3, pData, 4);
EXPECT_STREQ(aOut, "");
str_hex(aOut, 4, pData, 4);
EXPECT_STREQ(aOut, "41 ");
str_hex(aOut, 5, pData, 4);
EXPECT_STREQ(aOut, "41 ");
str_hex(aOut, 6, pData, 4);
EXPECT_STREQ(aOut, "41 ");
str_hex(aOut, 7, pData, 4);
EXPECT_STREQ(aOut, "41 42 ");
str_hex(aOut, 8, pData, 4);
EXPECT_STREQ(aOut, "41 42 ");
}
TEST(Str, HexDecode) TEST(Str, HexDecode)
{ {
char aOut[5] = {'a', 'b', 'c', 'd', 0}; char aOut[5] = {'a', 'b', 'c', 'd', 0};