basic/hashmap: add hashops variant that does strdup/freeing on its own

So far, we'd use hashmap_free_free to free both keys and values along with
the hashmap. I think it's better to make this more encapsulated: in this variant
the way contents are freed can be decided when the hashmap is created, and
users of the hashmap can always use hashmap_free.
This commit is contained in:
Zbigniew Jędrzejewski-Szmek
2019-07-19 16:50:36 +02:00
parent 0bf2c5e5ec
commit 87da87846d
5 changed files with 60 additions and 0 deletions
+26
View File
@@ -1768,6 +1768,32 @@ int set_consume(Set *s, void *value) {
return r;
}
int hashmap_put_strdup(Hashmap **h, const char *k, const char *v) {
int r;
r = hashmap_ensure_allocated(h, &string_hash_ops_free_free);
if (r < 0)
return r;
_cleanup_free_ char *kdup = NULL, *vdup = NULL;
kdup = strdup(k);
vdup = strdup(v);
if (!kdup || !vdup)
return -ENOMEM;
r = hashmap_put(*h, kdup, vdup);
if (r < 0) {
if (r == -EEXIST && streq(v, hashmap_get(*h, kdup)))
return 0;
return r;
}
assert(r > 0); /* 0 would mean vdup is already in the hashmap, which cannot be */
kdup = vdup = NULL;
return 0;
}
int set_put_strdup(Set *s, const char *p) {
char *c;