From: Zbigniew Jędrzejewski-Szmek Date: Wed, 3 Jun 2020 12:25:18 +0000 (+0200) Subject: basic/set: add set_ensure_put() X-Git-Tag: v246-rc1~105^2~17 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=0f9ccd95525c9869b6a23b71f6b7dbb2a7038674;p=thirdparty%2Fsystemd.git basic/set: add set_ensure_put() It's such a common operation to allocate the set and put an item in it, that it deserves a helper. set_ensure_put() has the same return values as set_put(). Comes with tests! --- diff --git a/src/basic/hashmap.c b/src/basic/hashmap.c index 15c8c4723c0..c876662a0bf 100644 --- a/src/basic/hashmap.c +++ b/src/basic/hashmap.c @@ -1247,6 +1247,16 @@ int set_put(Set *s, const void *key) { return hashmap_put_boldly(s, hash, &swap, true); } +int _set_ensure_put(Set **s, const struct hash_ops *hash_ops, const void *key HASHMAP_DEBUG_PARAMS) { + int r; + + r = _set_ensure_allocated(s, hash_ops HASHMAP_DEBUG_PASS_ARGS); + if (r < 0) + return r; + + return set_put(*s, key); +} + int hashmap_replace(Hashmap *h, const void *key, void *value) { struct swap_entries swap; struct plain_hashmap_entry *e; diff --git a/src/basic/set.h b/src/basic/set.h index 621e83bf277..cdc4abaa42f 100644 --- a/src/basic/set.h +++ b/src/basic/set.h @@ -120,6 +120,9 @@ static inline char **set_get_strv(Set *s) { return _hashmap_get_strv(HASHMAP_BASE(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) + int set_consume(Set *s, void *value); int set_put_strdup(Set **s, const char *p); int set_put_strdupv(Set **s, char **l); diff --git a/src/test/test-set.c b/src/test/test-set.c index 9c93685dbce..7213abda01c 100644 --- a/src/test/test-set.c +++ b/src/test/test-set.c @@ -107,6 +107,27 @@ static void test_set_put_strdupv(void) { assert_se(set_size(m) == 3); } +static void test_set_ensure_allocated(void) { + _cleanup_set_free_ Set *m = NULL; + + assert_se(set_ensure_allocated(&m, &string_hash_ops) == 1); + assert_se(set_ensure_allocated(&m, &string_hash_ops) == 0); + assert_se(set_ensure_allocated(&m, NULL) == 0); + assert_se(set_size(m) == 0); +} + +static void test_set_ensure_put(void) { + _cleanup_set_free_ Set *m = NULL; + + assert_se(set_ensure_put(&m, &string_hash_ops, "a") == 1); + assert_se(set_ensure_put(&m, &string_hash_ops, "a") == 0); + assert_se(set_ensure_put(&m, NULL, "a") == 0); + assert_se(set_ensure_put(&m, &string_hash_ops, "b") == 1); + assert_se(set_ensure_put(&m, &string_hash_ops, "b") == 0); + assert_se(set_ensure_put(&m, &string_hash_ops, "a") == 0); + assert_se(set_size(m) == 2); +} + int main(int argc, const char *argv[]) { test_set_steal_first(); test_set_free_with_destructor(); @@ -114,6 +135,8 @@ int main(int argc, const char *argv[]) { test_set_put(); test_set_put_strdup(); test_set_put_strdupv(); + test_set_ensure_allocated(); + test_set_ensure_put(); return 0; }