From caefa582e8d844ea75f2a72ca746e40227e0dc17 Mon Sep 17 00:00:00 2001 From: Alain Spineux Date: Fri, 20 Aug 2021 13:52:43 +0200 Subject: [PATCH] add built-in hexdump to bsnprintf() - sample char hash[MAX_HASH_SIZE]; int hash_size=32; /* notice that the length is the length in the output "buffer" not the length of the input buffer. This is like in any printf() "length" any char in the input will generate 2 digit in the output, you must multiply by 2 the size of the input buffer or get a small output! It is safe because bnsprintf() knows the length of its output buffer and truncate any overload */ Mmsg(0, "the hash is :%64W", hash); // fixed size Mmsg(0, "the hash is :%*W", 2*hash_size, hash); // variable size --- bacula/src/lib/bsnprintf.c | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/bacula/src/lib/bsnprintf.c b/bacula/src/lib/bsnprintf.c index f7d665083..5efad8e23 100644 --- a/bacula/src/lib/bsnprintf.c +++ b/bacula/src/lib/bsnprintf.c @@ -54,6 +54,8 @@ #endif int bvsnprintf(char *buffer, int32_t maxlen, const char *format, va_list args); +static int32_t fmthex(char *buffer, int32_t currlen, int32_t maxlen, + const char *value, int flags, int min, int max); static int32_t fmtstr(char *buffer, int32_t currlen, int32_t maxlen, const char *value, int flags, int min, int max); static int32_t fmtwstr(char *buffer, int32_t currlen, int32_t maxlen, @@ -352,6 +354,16 @@ int bvsnprintf(char *buffer, int32_t maxlen, const char *format, va_list args) currlen = fmtwstr(buffer, currlen, maxlen, wstrvalue, flags, min, max); } break; + case 'W': + /* hexadump of the length given by min */ + strvalue = va_arg(args, char *); + if (!strvalue) { + strvalue = (char *)""; + currlen = fmtstr(buffer, currlen, maxlen, strvalue, flags, min, max); + } else { + currlen = fmthex(buffer, currlen, maxlen, strvalue, flags, min, max); + } + break; case 'p': flags |= DP_F_UNSIGNED; if (sizeof(char *) == 4) { @@ -416,6 +428,24 @@ int bvsnprintf(char *buffer, int32_t maxlen, const char *format, va_list args) return currlen; } +static char hexatable[]="0123456789abcdef"; +static int32_t fmthex(char *buffer, int32_t currlen, int32_t maxlen, + const char *value, int flags, int min, int max) +{ + int i = 0; + + /* max is ignored for now */ + if (min <= 0) { + return 0; /* min is mandatory */ + } + while (i < min) { + outch(hexatable[(value[i]&0xF0)>>4]); + outch(hexatable[value[i]&0x0F]); + i++; + } + return currlen; +} + static int32_t fmtstr(char *buffer, int32_t currlen, int32_t maxlen, const char *value, int flags, int min, int max) { -- 2.47.3