]> git.ipfire.org Git - thirdparty/bacula.git/commitdiff
add built-in hexdump to bsnprintf()
authorAlain Spineux <alain@baculasystems.com>
Fri, 20 Aug 2021 11:52:43 +0000 (13:52 +0200)
committerEric Bollengier <eric@baculasystems.com>
Thu, 24 Mar 2022 08:03:03 +0000 (09:03 +0100)
- 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

index f7d665083f7d467c0027450be6e5d164499714d7..5efad8e23f72b98ee0a46bb9163d1d95a46ef586 100644 (file)
@@ -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 *)"<NULL>";
+               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)
 {