[PATCH 2/9] virstring: Introduce virStringIsNull()

Michal Privoznik mprivozn at redhat.com
Fri Jul 3 10:28:43 UTC 2020


This function will be used to detect zero buffers (which are
going to be interpreted as hole in virStream later).

I shamelessly took inspiration from coreutils.

Signed-off-by: Michal Privoznik <mprivozn at redhat.com>
---
 src/libvirt_private.syms |  1 +
 src/util/virstring.c     | 40 ++++++++++++++++++++++++++++++++++++++++
 src/util/virstring.h     |  2 ++
 3 files changed, 43 insertions(+)

diff --git a/src/libvirt_private.syms b/src/libvirt_private.syms
index ae0e253ab9..1d80aeb833 100644
--- a/src/libvirt_private.syms
+++ b/src/libvirt_private.syms
@@ -3197,6 +3197,7 @@ virStringHasChars;
 virStringHasControlChars;
 virStringHasSuffix;
 virStringIsEmpty;
+virStringIsNull;
 virStringIsPrintable;
 virStringListAdd;
 virStringListAutoFree;
diff --git a/src/util/virstring.c b/src/util/virstring.c
index e9e792f3bf..7f6871d5ab 100644
--- a/src/util/virstring.c
+++ b/src/util/virstring.c
@@ -1404,3 +1404,43 @@ int virStringParseYesNo(const char *str, bool *result)
 
     return 0;
 }
+
+
+/**
+ * virStringIsNull:
+ * @buf: buffer to check
+ * @len: the length of the buffer
+ *
+ * For given buffer @buf and its size @len determine whether
+ * it contains only zero bytes or not.
+ *
+ * Returns: true if buffer is full of zero bytes,
+ *          false otherwise.
+ */
+bool virStringIsNull(const char *buf, size_t len)
+{
+    const char *p = buf;
+
+    if (!len)
+        return true;
+
+    /* Check up to 16 first bytes. memcmp() below uses block of sizeof(long)
+     * size (in most cases on 64bits is 8 bytes), doing twice the size just to
+     * be safe. */
+    for (;;) {
+        if (*p)
+            return false;
+
+        p++;
+        len--;
+
+        if (!len)
+            return true;
+
+        if ((len & (2 * sizeof(long))) == 0)
+            break;
+    }
+
+    /* Now we know first 16 bytes are NUL, memcmp with self.  */
+    return memcmp(buf, p, len) == 0;
+}
diff --git a/src/util/virstring.h b/src/util/virstring.h
index 360c68395c..d0e54358ac 100644
--- a/src/util/virstring.h
+++ b/src/util/virstring.h
@@ -185,6 +185,8 @@ int virStringParsePort(const char *str,
 int virStringParseYesNo(const char *str,
                         bool *result)
     G_GNUC_WARN_UNUSED_RESULT;
+bool virStringIsNull(const char *buf, size_t len);
+
 /**
  * VIR_AUTOSTRINGLIST:
  *
-- 
2.26.2




More information about the libvir-list mailing list