For filtering lists of strings based on a predicate. --- daemon/daemon.h | 1 + daemon/utils.c | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/daemon/daemon.h b/daemon/daemon.h index 4d7504b3f..a16953f23 100644 --- a/daemon/daemon.h +++ b/daemon/daemon.h @@ -74,6 +74,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 (int (*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..1fc8d2c80 100644 --- a/daemon/utils.c +++ b/daemon/utils.c @@ -482,6 +482,28 @@ empty_list (void) return ret.argv; } +/** + * Filter a list of strings. Returns a newly allocated list of only + * the strings where C<p (str) != 0>. + */ +char ** +filter_list (int (*p) (const char *str), char **strs) +{ + DECLARE_STRINGSBUF (ret); + size_t i; + + for (i = 0; strs[i] != NULL; ++i) { + if (p (strs[i]) != 0) { + if (add_string (&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