Implement uc_hex_encode_delim without snprintf, fix length of

uc_hex_encode_delim when truncated output.
This commit is contained in:
Nils O. Selåsdal
2013-12-06 22:47:16 +01:00
parent 25f83f36ee
commit 59b4c3f57e
2 changed files with 28 additions and 10 deletions
+26 -9
View File
@@ -1,16 +1,18 @@
#include <stdint.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include "ucore/string.h"
#include "ucore/utils.h"
static const char hx_chars[] = "0123456789ABCDEF" ;
char*
uc_hex_encode(const uint8_t *in, size_t len, char *out)
{
unsigned int i, t, hn, ln;
unsigned int i, t;
for (i = 0, t = 0; i < len; ++i,t+=2) {
unsigned int hn, ln;
hn = (in[i] & 0xF0) >> 4 ;
ln = in[i] & 0x0F ;
@@ -27,19 +29,34 @@ uc_hex_encode(const uint8_t *in, size_t len, char *out)
char*
uc_hex_encode_delim(const uint8_t *in, size_t inlen, char *out, int outlen, char *delim)
{
unsigned int i;
size_t i;
char *outp = out;
out[0] = 0;
for (i = 0; i < inlen; i++) {
unsigned int hn, ln;
char *delimp = delim;
for (i = 0; i < inlen && outlen > 0; i++) {
int rc = snprintf(outp, outlen, "%02X%s", in[i], delim);
if (rc <= 0)
/** Truncate at a full byte */
if (outlen <= 2) {
break;
outp += rc;
outlen -= rc;
}
hn = (in[i] & 0xF0) >> 4 ;
ln = in[i] & 0x0F ;
outp[0] = hx_chars[hn];
outp[1] = hx_chars[ln];
outlen -= 2;
outp += 2;
while (outlen > 1 && *delimp) {
*outp++ = *delimp++;
outlen--;
}
}
*outp = 0;
return outp;
}
+2 -1
View File
@@ -135,6 +135,7 @@ START_TEST (test_uc_hex_encode_delim_1)
res = uc_hex_encode_delim(binary, sizeof binary, hex, sizeof hex, " ");
fail_if(strcmp(hex, "FF 00 7F 0A ") != 0, "hex was '%s'", hex);
*res = 0;
fail_if(res != hex + 12);
END_TEST
@@ -147,7 +148,7 @@ START_TEST (test_uc_hex_encode_delim_2)
res = uc_hex_encode_delim(binary, sizeof binary, hex, sizeof hex, " \n");
fail_if(strcmp(hex, "FF \n00 ") != 0, "hex was '%s'", hex);
fail_if(res != hex + 8);
fail_if(res != hex + 7, "sz was %zu", res - hex);
END_TEST