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 <max@sdn.clinic>
This commit is contained in:
parent
b1dfa609f9
commit
f51c976b52
2 changed files with 26 additions and 0 deletions
|
@ -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)
|
||||
{
|
||||
|
|
|
@ -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);
|
||||
|
|
Loading…
Reference in a new issue