[Libguestfs] [PATCH libguestfs v2 2/3] daemon: Add filter_list utility function.

Richard W.M. Jones rjones at redhat.com
Mon Mar 16 13:59:28 UTC 2020


For filtering lists of strings based on a predicate.
---
 daemon/daemon.h |  2 ++
 daemon/utils.c  | 26 ++++++++++++++++++++++++++
 2 files changed, 28 insertions(+)

diff --git a/daemon/daemon.h b/daemon/daemon.h
index 4d7504b3f..9a5ac6d42 100644
--- a/daemon/daemon.h
+++ b/daemon/daemon.h
@@ -22,6 +22,7 @@
 #include <stdio.h>
 #include <stdarg.h>
 #include <stdint.h>
+#include <stdbool.h>
 #include <errno.h>
 #include <unistd.h>
 
@@ -74,6 +75,7 @@ extern void free_stringsbuf (struct stringsbuf *sb);
 extern struct stringsbuf split_lines_sb (char *str);
 extern char **split_lines (char *str);
 extern char **empty_list (void);
+extern char **filter_list (bool (*p) (const char *), char **strs);
 extern int is_power_of_2 (unsigned long v);
 extern void trim (char *str);
 extern int parse_btrfsvol (const char *desc, mountable_t *mountable);
diff --git a/daemon/utils.c b/daemon/utils.c
index 1cf1b07f6..21008b40e 100644
--- a/daemon/utils.c
+++ b/daemon/utils.c
@@ -24,6 +24,7 @@
 
 #include <stdio.h>
 #include <stdlib.h>
+#include <stdbool.h>
 #include <string.h>
 #include <unistd.h>
 #include <rpc/types.h>
@@ -482,6 +483,31 @@ empty_list (void)
   return ret.argv;
 }
 
+/**
+ * Filter a list of strings.  Returns a newly allocated list of only
+ * the strings where C<p (str) == true>.
+ *
+ * B<Note> it does not copy the strings, be careful not to double-free
+ * them.
+ */
+char **
+filter_list (bool (*p) (const char *str), char **strs)
+{
+  DECLARE_STRINGSBUF (ret);
+  size_t i;
+
+  for (i = 0; strs[i] != NULL; ++i) {
+    if (p (strs[i])) {
+      if (add_string_nodup (&ret, strs[i]) == -1)
+        return NULL;
+    }
+  }
+  if (end_stringsbuf (&ret) == -1)
+    return NULL;
+
+  return take_stringsbuf (&ret);
+}
+
 /**
  * Skip leading and trailing whitespace, updating the original string
  * in-place.
-- 
2.25.0




More information about the Libguestfs mailing list