]> git.ipfire.org Git - thirdparty/suricata.git/commitdiff
byte: add bytes to string w/o allocation
authorVictor Julien <victor@inliniac.net>
Wed, 12 Dec 2018 13:35:11 +0000 (14:35 +0100)
committerVictor Julien <victor@inliniac.net>
Wed, 20 Feb 2019 13:45:18 +0000 (14:45 +0100)
src/util-byte.c
src/util-byte.h

index 81efe1973cc33c8b88adf2e3395e590840bad8d5..db33a4ba5d441bb0504883d745b2ba1122d290f0 100644 (file)
@@ -27,6 +27,7 @@
 #include "util-byte.h"
 #include "util-unittest.h"
 #include "util-debug.h"
+#include "util-validate.h"
 
 /** \brief Turn byte array into string.
  *
@@ -71,6 +72,53 @@ char *BytesToString(const uint8_t *bytes, size_t nbytes)
     return string;
 }
 
+/** \brief Turn byte array into string.
+ *
+ *  All non-printables are copied over, except for '\0', which is
+ *  turned into literal \0 in the string.
+ *
+ *  \param bytes byte array
+ *  \param nbytes number of bytes
+ *  \param outstr[out] buffer to fill
+ *  \param outlen size of outstr. Must be at least 2 * nbytes + 1 in size
+ */
+void BytesToStringBuffer(const uint8_t *bytes, size_t nbytes, char *outstr, size_t outlen)
+{
+    DEBUG_VALIDATE_BUG_ON(outlen < (nbytes * 2 + 1));
+
+    size_t n = nbytes + 1;
+    size_t nulls = 0;
+
+    size_t u;
+    for (u = 0; u < nbytes; u++) {
+        if (bytes[u] == '\0')
+            nulls++;
+    }
+    n += nulls;
+
+    char string[n];
+
+    if (nulls == 0) {
+        /* no nulls */
+        memcpy(string, bytes, nbytes);
+        string[nbytes] = '\0';
+    } else {
+        /* nulls present */
+        char *dst = string;
+        for (u = 0; u < nbytes; u++) {
+            if (bytes[u] == '\0') {
+                *dst++ = '\\';
+                *dst++ = '0';
+            } else {
+                *dst++ = bytes[u];
+            }
+        }
+        *dst = '\0';
+    }
+
+    strlcpy(outstr, string, outlen);
+}
+
 int ByteExtractUint64(uint64_t *res, int e, uint16_t len, const uint8_t *bytes)
 {
     uint64_t i64;
index aca846ac2bfe46564481889a83e522531242382d..08986ea5046f516e670ab6b3a870af9cdd92b2b0 100644 (file)
@@ -81,6 +81,7 @@
  *  \return string nul-terminated string or NULL on error
  */
 char *BytesToString(const uint8_t *bytes, size_t nbytes);
+void BytesToStringBuffer(const uint8_t *bytes, size_t nbytes, char *outstr, size_t outlen);
 
 /**
  * Extract bytes from a byte string and convert to a unint64_t.