Add format_hexdump function 70/1470/4
authorDamjan Marion <[email protected]>
Thu, 9 Jun 2016 10:38:22 +0000 (12:38 +0200)
committerChris Luke <[email protected]>
Thu, 9 Jun 2016 17:23:22 +0000 (17:23 +0000)
Function output is compatible with text2pcap tool

Sample output:

00000: 54 68 65 20 71 75 69 63 6b 20 62 72 6f 77 6e 20 [The quick brown ]
00010: 66 6f 78 20 6a 75 6d 70 73 20 6f 76 65 72 20 74 [fox jumps over t]
00020: 68 65 20 6c 61 7a 79 20 64 6f 67 00             [he lazy dog.]

Change-Id: If77ec7d91b77146df770698e0cf35fe2f6dd0821
Signed-off-by: Damjan Marion <[email protected]>
vppinfra/vppinfra/format.h
vppinfra/vppinfra/std-formats.c

index 62669cd..45cd3f5 100644 (file)
@@ -297,6 +297,9 @@ u8 * format_memory_size (u8 * s, va_list * va);
 /* Format c identifier: e.g. a_name -> "a name". */
 u8 * format_c_identifier (u8 * s, va_list * va);
 
+/* Format hexdump with both hex and printable chars - compatible with text2pcap */
+u8 * format_hexdump (u8 * s, va_list * va);
+
 /* Unix specific formats. */
 #ifdef CLIB_UNIX
 /* Setup input from Unix file. */
index 9bc5816..b47d8fb 100644 (file)
@@ -36,6 +36,7 @@
 */
 
 #include <vppinfra/format.h>
+#include <ctype.h>
 
 /* Format vectors. */
 u8 * format_vec32 (u8 * s, va_list * va)
@@ -257,3 +258,48 @@ u8 * format_c_identifier (u8 * s, va_list * va)
 
   return s;
 }
+
+u8 *
+format_hexdump (u8 * s, va_list * args)
+{
+  u8 * data = va_arg (*args, u8 *);
+  uword len = va_arg (*args, uword);
+  int i, index =0;
+  const int line_len = 16;
+  u8 * line_hex = 0;
+  u8 * line_str = 0;
+  uword indent = format_get_indent (s);
+
+  if (!len)
+    return s;
+
+  for(i=0; i < len; i++)
+    {
+      line_hex = format (line_hex, "%02x ",  data[i]);
+      line_str = format (line_str, "%c", isprint (data[i]) ? data[i] : '.');
+      if (!( (i + 1) % line_len))
+       {
+         s = format (s, "%U%05x: %v[%v]",
+                     format_white_space, index ? indent : 0,
+                     index, line_hex, line_str);
+         if (i < len - 1)
+           s = format (s, "\n");
+         index = i + 1;
+         vec_reset_length(line_hex);
+         vec_reset_length(line_str);
+       }
+    }
+
+  while (i++ % line_len)
+    line_hex = format (line_hex, "   ");
+
+  if (vec_len(line_hex))
+    s = format (s, "%U%05x: %v[%v]",
+               format_white_space, indent,
+               index, line_hex, line_str);
+
+  vec_free(line_hex);
+  vec_free(line_str);
+
+  return s;
+}