1
1
mirror of https://github.com/systemd/systemd-stable.git synced 2024-12-22 13:33:56 +03:00

set: add set_make_nulstr

Add function set_make_nulstr() to create a nulstr out of a set. Behave
the same way as strv_make_nulstr().
This commit is contained in:
Quentin Deslandes 2022-11-07 20:25:46 +01:00
parent c68523e00d
commit 96c648fecd
3 changed files with 63 additions and 0 deletions

View File

@ -115,6 +115,21 @@ int strv_make_nulstr(char * const *l, char **ret, size_t *ret_size) {
return 0;
}
int set_make_nulstr(Set *s, char **ret, size_t *ret_size) {
/* Use _cleanup_free_ instead of _cleanup_strv_free_ because we need to clean the strv only, not
* the strings owned by the set. */
_cleanup_free_ char **strv = NULL;
assert(ret);
assert(ret_size);
strv = set_get_strv(s);
if (!strv)
return -ENOMEM;
return strv_make_nulstr(strv, ret, ret_size);
}
const char* nulstr_get(const char *nulstr, const char *needle) {
if (!nulstr)
return NULL;

View File

@ -6,6 +6,8 @@
#include <stdbool.h>
#include <string.h>
#include "set.h"
#define NULSTR_FOREACH(i, l) \
for (typeof(*(l)) *(i) = (l); (i) && *(i); (i) = strchr((i), 0)+1)
@ -21,6 +23,7 @@ static inline bool nulstr_contains(const char *nulstr, const char *needle) {
char** strv_parse_nulstr(const char *s, size_t l);
char** strv_split_nulstr(const char *s);
int strv_make_nulstr(char * const *l, char **p, size_t *n);
int set_make_nulstr(Set *s, char **ret, size_t *ret_size);
static inline int strv_from_nulstr(char ***ret, const char *nulstr) {
char **t;

View File

@ -2,6 +2,7 @@
#include "alloc-util.h"
#include "nulstr-util.h"
#include "set.h"
#include "strv.h"
#include "tests.h"
@ -129,6 +130,50 @@ TEST(strv_make_nulstr) {
test_strv_make_nulstr_one(STRV_MAKE("foo", "bar", "quuux"));
}
TEST(set_make_nulstr) {
_cleanup_set_free_free_ Set *set = NULL;
size_t len = 0;
int r;
{
/* Unallocated and empty set. */
char expect[] = { 0x00, 0x00 };
_cleanup_free_ char *nulstr = NULL;
r = set_make_nulstr(set, &nulstr, &len);
assert_se(r == 0);
assert_se(len == 0);
assert_se(memcmp(expect, nulstr, len + 2) == 0);
}
{
/* Allocated by empty set. */
char expect[] = { 0x00, 0x00 };
_cleanup_free_ char *nulstr = NULL;
set = set_new(NULL);
assert_se(set);
r = set_make_nulstr(set, &nulstr, &len);
assert_se(r == 0);
assert_se(len == 0);
assert_se(memcmp(expect, nulstr, len + 2) == 0);
}
{
/* Non-empty set. */
char expect[] = { 'a', 'a', 'a', 0x00, 0x00 };
_cleanup_free_ char *nulstr = NULL;
assert_se(set_put_strdup(&set, "aaa") >= 0);
r = set_make_nulstr(set, &nulstr, &len);
assert_se(r == 0);
assert_se(len == 4);
assert_se(memcmp(expect, nulstr, len + 1) == 0);
}
}
static void test_strv_make_nulstr_binary_one(char **l, const char *b, size_t n) {
_cleanup_strv_free_ char **z = NULL;
_cleanup_free_ char *a = NULL;