[Spice-devel] [PATCH libcacard 08/45] hex_dump: Helper function to allow inspection of internal buffers
Jakub Jelen
jjelen at redhat.com
Tue Jul 31 14:50:02 UTC 2018
Signed-off-by: Jakub Jelen <jjelen at redhat.com>
Reviewed-by: Robert Relyea <rrelyea at redhat.com>
---
src/common.c | 40 ++++++++++++++++++++++++++++++++++++++++
src/common.h | 2 ++
2 files changed, 42 insertions(+)
diff --git a/src/common.c b/src/common.c
index 521ef51..2e06314 100644
--- a/src/common.c
+++ b/src/common.c
@@ -26,7 +26,9 @@
#endif
#include <stddef.h>
+#include <stdio.h>
+#include "vcard.h"
#include "common.h"
unsigned char *
@@ -46,4 +48,42 @@ lebytes2ushort(const unsigned char *buf)
return 0U;
return (unsigned short)buf[1] << 8 | (unsigned short)buf[0];
}
+
+#define MAX_STATIC_BYTES 1024
+static char hexdump_buffer[5*MAX_STATIC_BYTES];
+/*
+ * Creates printable representation in hexadecimal format of the data
+ * provided in the buf buffer. If out buffer is provided, the data
+ * will be written into it. Otherwise, static buffer will be used, which
+ * can hold up to 1024 bytes (longer will get truncated).
+ */
+char *
+hex_dump(unsigned char *buf, size_t buflen, unsigned char **out, size_t outlen)
+{
+ char *p, *start;
+ size_t i, expect_len = buflen*5;
+
+ if (buflen <= 0)
+ return NULL;
+
+ if (out == NULL) {
+ start = hexdump_buffer;
+ buflen = MIN(buflen, MAX_STATIC_BYTES);
+ } else {
+ if (outlen < expect_len) {
+ /* too short output buffer */
+ return NULL;
+ }
+ start = (char *) *out;
+ }
+
+ p = start;
+ for (i = 0; i < buflen; i++) {
+ sprintf(p, "0x%02X ", buf[i]);
+ p += 5;
+ }
+ /* terminate */
+ *--p = '\x00';
+ return start;
+}
/* vim: set ts=4 sw=4 tw=0 noet expandtab: */
diff --git a/src/common.h b/src/common.h
index 83c8f33..e9fae67 100644
--- a/src/common.h
+++ b/src/common.h
@@ -27,4 +27,6 @@
unsigned char *ushort2lebytes(unsigned char *buf, unsigned short x);
unsigned short lebytes2ushort(const unsigned char *buf);
+char *hex_dump(unsigned char *, size_t, unsigned char **, size_t);
+
#endif
--
2.17.1
More information about the Spice-devel
mailing list