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!
This commit is contained in:
Zbigniew Jędrzejewski-Szmek 2020-06-03 14:25:18 +02:00
parent aaffd34933
commit 0f9ccd9552
3 changed files with 36 additions and 0 deletions

View File

@ -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;

View File

@ -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);

View File

@ -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;
}