Commit 578c4bfb authored by Jon Griffiths's avatar Jon Griffiths

hex: Simplify hex_encode

The documentation for hex_encode indicates that it returns simply true or
false. The old implementation was returning the written length on success,
cast to boolean. This will elicit a warning under MSVC.

On further examination, there is no need to check/modify the length inside
the loop, since we can check it once before starting. As a result the code
can be simplified a bit.

A side affect of this change is that nothing will be written at all if the
length is incorrect, vs the previous code writing characters until the length
available is exhausted. I prefer the new semantics but YMMV.
Signed-off-by: default avatarJon Griffiths <jon_p_griffiths@yahoo.com>
parent be24e496
...@@ -50,21 +50,17 @@ static char hexchar(unsigned int val) ...@@ -50,21 +50,17 @@ static char hexchar(unsigned int val)
bool hex_encode(const void *buf, size_t bufsize, char *dest, size_t destsize) bool hex_encode(const void *buf, size_t bufsize, char *dest, size_t destsize)
{ {
size_t used = 0; size_t i;
if (destsize < 1) if (destsize < hex_str_size(bufsize))
return false; return false;
while (used < bufsize) { for (i = 0; i < bufsize; i++) {
unsigned int c = ((const unsigned char *)buf)[used]; unsigned int c = ((const unsigned char *)buf)[i];
if (destsize < 3)
return false;
*(dest++) = hexchar(c >> 4); *(dest++) = hexchar(c >> 4);
*(dest++) = hexchar(c & 0xF); *(dest++) = hexchar(c & 0xF);
used++;
destsize -= 2;
} }
*dest = '\0'; *dest = '\0';
return used + 1; return true;
} }
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment