basic/set: add set_ensure_consume()

This combines set_ensure_allocated() with set_consume(). The cool thing is that
because we know the hash ops, we can correctly free the item if appropriate.
Similarly to set_consume(), the goal is to simplify handling of the case where
the item needs to be freed on error and if already present in the set.
This commit is contained in:
Zbigniew Jędrzejewski-Szmek
2020-06-24 10:38:15 +02:00
parent 6cd55d6f74
commit fcc1d0315d
4 changed files with 42 additions and 0 deletions
+23
View File
@@ -128,6 +128,28 @@ static void test_set_ensure_put(void) {
assert_se(set_size(m) == 2);
}
static void test_set_ensure_consume(void) {
_cleanup_set_free_ Set *m = NULL;
char *s, *t;
assert_se(s = strdup("a"));
assert_se(set_ensure_consume(&m, &string_hash_ops_free, s) == 1);
assert_se(t = strdup("a"));
assert_se(set_ensure_consume(&m, &string_hash_ops_free, t) == 0);
assert_se(t = strdup("a"));
assert_se(set_ensure_consume(&m, &string_hash_ops_free, t) == 0);
assert_se(t = strdup("b"));
assert_se(set_ensure_consume(&m, &string_hash_ops_free, t) == 1);
assert_se(t = strdup("b"));
assert_se(set_ensure_consume(&m, &string_hash_ops_free, t) == 0);
assert_se(set_size(m) == 2);
}
int main(int argc, const char *argv[]) {
test_set_steal_first();
test_set_free_with_destructor();
@@ -137,6 +159,7 @@ int main(int argc, const char *argv[]) {
test_set_put_strdupv();
test_set_ensure_allocated();
test_set_ensure_put();
test_set_ensure_consume();
return 0;
}