From: Yu Watanabe Date: Mon, 27 Jan 2025 23:50:14 +0000 (+0900) Subject: strv: introduce string_strv_hashmap_remove() X-Git-Tag: v258-rc1~1373^2~3 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=c540875cd3b024f64980966376637ecc284d643c;p=thirdparty%2Fsystemd.git strv: introduce string_strv_hashmap_remove() --- diff --git a/src/basic/strv.c b/src/basic/strv.c index d817140cc98..1eea73fa7b7 100644 --- a/src/basic/strv.c +++ b/src/basic/strv.c @@ -1063,6 +1063,23 @@ int fputstrv(FILE *f, char * const *l, const char *separator, bool *space) { return 0; } +void string_strv_hashmap_remove(Hashmap *h, const char *key, const char *value) { + assert(key); + + if (value) { + char **l = hashmap_get(h, key); + if (!l) + return; + + strv_remove(l, value); + if (!strv_isempty(l)) + return; + } + + _unused_ _cleanup_free_ char *key_free = NULL; + strv_free(hashmap_remove2(h, key, (void**) &key_free)); +} + static int string_strv_hashmap_put_internal(Hashmap *h, const char *key, const char *value) { char **l; int r; diff --git a/src/basic/strv.h b/src/basic/strv.h index 86ba06f835a..5cdc801f35a 100644 --- a/src/basic/strv.h +++ b/src/basic/strv.h @@ -258,6 +258,10 @@ int fputstrv(FILE *f, char * const *l, const char *separator, bool *space); #define strv_free_and_replace(a, b) \ free_and_replace_full(a, b, strv_free) +void string_strv_hashmap_remove(Hashmap *h, const char *key, const char *value); +static inline void string_strv_ordered_hashmap_remove(OrderedHashmap *h, const char *key, const char *value) { + string_strv_hashmap_remove(PLAIN_HASHMAP(h), key, value); +} int _string_strv_hashmap_put(Hashmap **h, const char *key, const char *value HASHMAP_DEBUG_PARAMS); int _string_strv_ordered_hashmap_put(OrderedHashmap **h, const char *key, const char *value HASHMAP_DEBUG_PARAMS); #define string_strv_hashmap_put(h, k, v) _string_strv_hashmap_put(h, k, v HASHMAP_DEBUG_SRC_ARGS) diff --git a/src/test/test-hashmap-plain.c b/src/test/test-hashmap-plain.c index 6b6058b08ac..6bcf353887f 100644 --- a/src/test/test-hashmap-plain.c +++ b/src/test/test-hashmap-plain.c @@ -973,6 +973,22 @@ TEST(string_strv_hashmap) { s = hashmap_get(m, "xxx"); assert_se(strv_equal(s, STRV_MAKE("bar", "BAR"))); + + string_strv_hashmap_remove(m, "foo", "bar"); + ASSERT_NOT_NULL(s = hashmap_get(m, "foo")); + ASSERT_TRUE(strv_equal(s, STRV_MAKE("BAR"))); + + string_strv_hashmap_remove(m, "foo", "BAR"); + ASSERT_NULL(hashmap_get(m, "foo")); + + string_strv_hashmap_remove(m, "xxx", "BAR"); + ASSERT_NOT_NULL(s = hashmap_get(m, "xxx")); + ASSERT_TRUE(strv_equal(s, STRV_MAKE("bar"))); + + string_strv_hashmap_remove(m, "xxx", "bar"); + ASSERT_NULL(hashmap_get(m, "xxx")); + + ASSERT_TRUE(hashmap_isempty(m)); } TEST(hashmap_dump_sorted) {