Skip to content

Commit

Permalink
daemon: Add filter_list utility function.
Browse files Browse the repository at this point in the history
For filtering lists of strings based on a predicate.
  • Loading branch information
rwmjones committed Mar 30, 2020
1 parent 5c175fe commit af8ed26
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
2 changes: 2 additions & 0 deletions daemon/daemon.h
Expand Up @@ -22,6 +22,7 @@
#include <stdio.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdbool.h>
#include <errno.h>
#include <unistd.h>

Expand Down Expand Up @@ -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);
Expand Down
30 changes: 30 additions & 0 deletions daemon/utils.c
Expand Up @@ -24,6 +24,7 @@

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <rpc/types.h>
Expand Down Expand Up @@ -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.
Expand Down

0 comments on commit af8ed26

Please sign in to comment.