From f51c976b528fd21ea7177325f18d9db7fd54aa92 Mon Sep 17 00:00:00 2001 From: Maximilian Wilhelm Date: Tue, 28 Jul 2020 22:44:22 +0200 Subject: [PATCH] dict: Add lif_dict_add_once() Add a function to add a key/value pair to the dict only if it doesn't exist within the dict already. As the dict is type agnostic this requires a comparator function to be given. Signed-off-by: Maximilian Wilhelm --- libifupdown/dict.c | 25 +++++++++++++++++++++++++ libifupdown/dict.h | 1 + 2 files changed, 26 insertions(+) diff --git a/libifupdown/dict.c b/libifupdown/dict.c index ce7333d..a0b5f2a 100644 --- a/libifupdown/dict.c +++ b/libifupdown/dict.c @@ -50,6 +50,31 @@ lif_dict_add(struct lif_dict *dict, const char *key, void *data) return entry; } +struct lif_dict_entry * +lif_dict_add_once(struct lif_dict *dict, const char *key, void *data, + int (*compar)(const void *, const void *)) +{ + struct lif_list *existing = lif_dict_find_all(dict, key); + if (existing) + { + struct lif_node *iter; + LIF_LIST_FOREACH(iter, existing->head) + { + if (!compar(data, iter->data)) + return NULL; + } + } + + struct lif_dict_entry *entry = calloc(1, sizeof *entry); + + entry->key = strdup(key); + entry->data = data; + + lif_node_insert_tail(&entry->node, entry, &dict->list); + + return entry; +} + struct lif_dict_entry * lif_dict_find(struct lif_dict *dict, const char *key) { diff --git a/libifupdown/dict.h b/libifupdown/dict.h index f435916..2332c05 100644 --- a/libifupdown/dict.h +++ b/libifupdown/dict.h @@ -38,6 +38,7 @@ struct lif_dict_entry { extern void lif_dict_init(struct lif_dict *dict); extern void lif_dict_fini(struct lif_dict *dict); extern struct lif_dict_entry *lif_dict_add(struct lif_dict *dict, const char *key, void *data); +extern struct lif_dict_entry *lif_dict_add_once(struct lif_dict *dict, const char *key, void *data, int (*compar)(const void *, const void *)); extern struct lif_dict_entry *lif_dict_find(struct lif_dict *dict, const char *key); extern struct lif_list *lif_dict_find_all(struct lif_dict *dict, const char *key); extern void lif_dict_delete(struct lif_dict *dict, const char *key);