util: Add common hex dump utility
authorAlyssa Rosenzweig <alyssa@rosenzweig.io>
Wed, 17 May 2023 21:29:44 +0000 (17:29 -0400)
committerMarge Bot <emma+marge@anholt.net>
Fri, 19 May 2023 16:30:44 +0000 (16:30 +0000)
Useful for debugging.

Signed-off-by: Alyssa Rosenzweig <alyssa@rosenzweig.io>
Acked-by: Boris Brezillon <boris.brezillon@collabora.com>
Part-of: <https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/23088>

src/util/u_hexdump.h [new file with mode: 0644]

diff --git a/src/util/u_hexdump.h b/src/util/u_hexdump.h
new file mode 100644 (file)
index 0000000..9c79fc2
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright 2021 Alyssa Rosenzweig
+ * SPDX-License-Identifier: MIT
+ */
+
+#ifndef U_HEXDUMP_H
+#define U_HEXDUMP_H
+
+#include <stdio.h>
+#include <stdbool.h>
+
+static inline void
+u_hexdump(FILE *fp, const uint8_t *hex, size_t cnt, bool with_strings)
+{
+   for (unsigned i = 0; i < cnt; ++i) {
+      if ((i & 0xF) == 0)
+         fprintf(fp, "%06X  ", i);
+
+      uint8_t v = hex[i];
+
+      if (v == 0 && (i & 0xF) == 0) {
+         /* Check if we're starting an aligned run of zeroes */
+         unsigned zero_count = 0;
+
+         for (unsigned j = i; j < cnt; ++j) {
+            if (hex[j] == 0)
+               zero_count++;
+            else
+               break;
+         }
+
+         if (zero_count >= 32) {
+            fprintf(fp, "*\n");
+            i += (zero_count & ~0xF) - 1;
+            continue;
+         }
+      }
+
+      fprintf(fp, "%02X ", hex[i]);
+      if ((i & 0xF) == 0xF && with_strings) {
+         fprintf(fp, " | ");
+         for (unsigned j = i & ~0xF; j <= i; ++j) {
+            uint8_t c = hex[j];
+            fputc((c < 32 || c > 128) ? '.' : c, fp);
+         }
+      }
+
+      if ((i & 0xF) == 0xF)
+         fprintf(fp, "\n");
+   }
+
+   fprintf(fp, "\n");
+}
+
+#endif