From: Yu Watanabe Date: Fri, 11 Apr 2025 00:54:21 +0000 (+0900) Subject: set: introduce set_to_strv() X-Git-Tag: v258-rc1~829^2~3 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=24655047b06895d3552f700f4a6cf006b4dbced8;p=thirdparty%2Fsystemd.git set: introduce set_to_strv() It is similar to set_get_strv(), but invalidates the set on success. --- diff --git a/src/basic/hashmap.c b/src/basic/hashmap.c index 951f63ae6da..a547b8c31cb 100644 --- a/src/basic/hashmap.c +++ b/src/basic/hashmap.c @@ -1805,6 +1805,23 @@ char** _hashmap_get_strv(HashmapBase *h) { return sv; } +char** set_to_strv(Set **s) { + assert(s); + + /* This is similar to set_get_strv(), but invalidates the set on success. */ + + char **v = new(char*, set_size(*s) + 1); + if (!v) + return NULL; + + for (char **p = v; (*p = set_steal_first(*s)); p++) + ; + + assert(set_isempty(*s)); + *s = set_free(*s); + return v; +} + void* ordered_hashmap_next(OrderedHashmap *h, const void *key) { struct ordered_hashmap_entry *e; unsigned hash, idx; diff --git a/src/basic/set.h b/src/basic/set.h index 618e7297446..05d7d88875e 100644 --- a/src/basic/set.h +++ b/src/basic/set.h @@ -114,6 +114,8 @@ static inline char **set_get_strv(Set *s) { return _hashmap_get_strv(HASHMAP_BASE(s)); } +char** set_to_strv(Set **s); + int _set_ensure_put(Set **s, const struct hash_ops *hash_ops, const void *key HASHMAP_DEBUG_PARAMS); #define set_ensure_put(s, hash_ops, key) _set_ensure_put(s, hash_ops, key HASHMAP_DEBUG_SRC_ARGS) diff --git a/src/test/test-set.c b/src/test/test-set.c index f1e6e9314b5..19b46a529fa 100644 --- a/src/test/test-set.c +++ b/src/test/test-set.c @@ -400,4 +400,28 @@ TEST(set_fnmatch) { assert_se(!set_fnmatch(match, nomatch, "cccXX")); } +TEST(set_to_strv) { + _cleanup_set_free_ Set *set = NULL; + _cleanup_strv_free_ char **a = NULL; + _cleanup_free_ char **b = NULL; + char **v = STRV_MAKE("aaa", "bbb", "ccc"); + + ASSERT_NOT_NULL(a = set_to_strv(&set)); + ASSERT_TRUE(strv_isempty(a)); + ASSERT_NULL(set); + a = strv_free(a); + + ASSERT_OK(set_put_strdupv(&set, v)); + ASSERT_EQ(set_size(set), strv_length(v)); + + ASSERT_NOT_NULL(b = set_get_strv(set)); + ASSERT_EQ(strv_length(b), strv_length(v)); + ASSERT_TRUE(strv_equal_ignore_order(b, v)); + + ASSERT_NOT_NULL(a = set_to_strv(&set)); + ASSERT_EQ(strv_length(a), strv_length(v)); + ASSERT_TRUE(strv_equal_ignore_order(a, v)); + ASSERT_NULL(set); +} + DEFINE_TEST_MAIN(LOG_INFO);