Skip to content

Commit

Permalink
Merge pull request teeworlds#3249 from ChillerDragon/pr_fix_str_hex
Browse files Browse the repository at this point in the history
Fix `str_hex` and add tests
  • Loading branch information
oy authored Jul 27, 2024
2 parents cb6ace6 + c73e902 commit d9f99ab
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 7 deletions.
15 changes: 8 additions & 7 deletions src/base/system.c
Original file line number Diff line number Diff line change
Expand Up @@ -2501,15 +2501,16 @@ const char *str_find(const char *haystack, const char *needle)
void str_hex(char *dst, int dst_size, const void *data, int data_size)
{
static const char hex[] = "0123456789ABCDEF";
int b;

for(b = 0; b < data_size && b < dst_size/4-4; b++)
int data_index;
int dst_index;
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[b*3+1] = hex[((const unsigned char *)data)[b]&0xf];
dst[b*3+2] = ' ';
dst[b*3+3] = 0;
dst[data_index * 3] = hex[((const unsigned char *)data)[data_index] >> 4];
dst[data_index * 3 + 1] = hex[((const unsigned char *)data)[data_index] & 0xf];
dst[data_index * 3 + 2] = ' ';
dst_index += 3;
}
dst[dst_index] = '\0';
}

int str_is_number(const char *str)
Expand Down
32 changes: 32 additions & 0 deletions src/test/str.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,38 @@

#include <base/system.h>

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, Startswith)
{
EXPECT_TRUE(str_startswith("abcdef", "abc"));
Expand Down

0 comments on commit d9f99ab

Please sign in to comment.