From 79903dd171cd7bdbb52710b98dbaa5de1537de87 Mon Sep 17 00:00:00 2001 From: Ben Pfaff Date: Wed, 30 Jun 2010 13:26:42 -0700 Subject: [PATCH] shash: New function shash_replace(). To be used in an upcoming commit. --- lib/shash.c | 20 ++++++++++++++++++++ lib/shash.h | 1 + 2 files changed, 21 insertions(+) diff --git a/lib/shash.c b/lib/shash.c index e2b1fe2c..1664baf6 100644 --- a/lib/shash.c +++ b/lib/shash.c @@ -147,6 +147,26 @@ shash_add_assert(struct shash *sh, const char *name, const void *data) assert(added); } +/* Searches for 'name' in 'sh'. If it does not already exist, adds it along + * with 'data' and returns NULL. If it does already exist, replaces its data + * by 'data' and returns the data that it formerly contained. */ +void * +shash_replace(struct shash *sh, const char *name, const void *data) +{ + size_t hash = hash_name(name); + struct shash_node *node; + + node = shash_find__(sh, name, hash); + if (!node) { + shash_add_nocopy__(sh, xstrdup(name), data, hash); + return NULL; + } else { + void *old_data = node->data; + node->data = (void *) data; + return old_data; + } +} + void shash_delete(struct shash *sh, struct shash_node *node) { diff --git a/lib/shash.h b/lib/shash.h index f97e6616..19e4c5d6 100644 --- a/lib/shash.h +++ b/lib/shash.h @@ -55,6 +55,7 @@ struct shash_node *shash_add(struct shash *, const char *, const void *); struct shash_node *shash_add_nocopy(struct shash *, char *, const void *); bool shash_add_once(struct shash *, const char *, const void *); void shash_add_assert(struct shash *, const char *, const void *); +void *shash_replace(struct shash *, const char *, const void *data); void shash_delete(struct shash *, struct shash_node *); struct shash_node *shash_find(const struct shash *, const char *); void *shash_find_data(const struct shash *, const char *); -- 2.30.2