daemon: Add filter_list utility function.

For filtering lists of strings based on a predicate.
This commit is contained in:
Richard W.M. Jones
2020-03-12 13:59:05 +00:00
parent 5c175fe732
commit af8ed266a2
2 changed files with 32 additions and 0 deletions

View File

@@ -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);

View File

@@ -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,35 @@ 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) {
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.