From 2e5a8775941b5767abcfcf93f9f84c9560e0f378 Mon Sep 17 00:00:00 2001 From: "Richard W.M. Jones" Date: Thu, 12 Mar 2020 13:59:05 +0000 Subject: [PATCH] daemon: Add filter_list utility function. For filtering lists of strings based on a predicate. (cherry picked from commit af8ed266a282bb20882a9ffb611bd64243d19218) --- daemon/daemon.h | 2 ++ daemon/utils.c | 30 ++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/daemon/daemon.h b/daemon/daemon.h index 66bfdc49e..115591728 100644 --- a/daemon/daemon.h +++ b/daemon/daemon.h @@ -22,6 +22,7 @@ #include #include #include +#include #include #include @@ -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 c3f88bcab..e87233d0f 100644 --- a/daemon/utils.c +++ b/daemon/utils.c @@ -24,6 +24,7 @@ #include #include +#include #include #include #include @@ -482,6 +483,35 @@ empty_list (void) return ret.argv; } +/** + * Filter a list of strings. Returns a newly allocated list of only + * the strings where C

. + * + * B 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) { + free (ret.argv); + return NULL; + } + } + } + if (end_stringsbuf (&ret) == -1) { + free (ret.argv); + return NULL; + } + + return take_stringsbuf (&ret); +} + /** * Skip leading and trailing whitespace, updating the original string * in-place. -- 2.18.4