From 51d368c20e1d93970a94cb0d2aff10654922bb37 Mon Sep 17 00:00:00 2001 From: Tucker Evans Date: Mon, 6 Jul 2020 19:47:22 -0400 Subject: Add insert function for maps --- collections/map/map.adoc | 24 +++++++++++++++++++++++- collections/map/map.c | 37 +++++++++++++++++++++++++++++++++++++ collections/map/map.h | 3 +++ 3 files changed, 63 insertions(+), 1 deletion(-) diff --git a/collections/map/map.adoc b/collections/map/map.adoc index 4668e0e..2b3e2cb 100644 --- a/collections/map/map.adoc +++ b/collections/map/map.adoc @@ -1,7 +1,7 @@ Map === Tucker Evans -v0.2, 2020-07-06 +v0.3, 2020-07-06 A basic map implemented in an AVL tree. @@ -70,6 +70,28 @@ map_insert(dict, "ONE", NULL); assert(map_size(dict) == 1); ---- +[[map_insert]] ++int map_insert(map *self, void *key, void *value)+ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Inserts item +value+ for +key+ into +self+ +This returns an int indicating a successful insertion; currently the only +two potential errors are caused by a NULL map or an equivalent key with a +different pointer, this is in order to prevent a memory leak. +<> can be used to fix this issue. + +Examples +^^^^^^^^ +[source,c] +---- +#include "map.h" +#include + +map *dict = map_new((cmp_func) strcmp); + +map_insert(dict, "ONE", NULL); +assert(map_size(dict) == 1); +---- + [[map_clear]] +void map_clear(map *self)+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/collections/map/map.c b/collections/map/map.c index 1b6cbaa..83a446d 100644 --- a/collections/map/map.c +++ b/collections/map/map.c @@ -45,6 +45,43 @@ map *root; return map_size(root->left) + map_size(root->right) + 1; } +int map_insert(root, key, val) +map *root; +void *key, *val; +{ + int cmp; + + if (!root) + return -1; + + if (!key) { + root->key = key; + root->val = val; + return 0; + } + + cmp = root->cmp(root->key, key); + + if (cmp == 0 && root->key == key) { + root->val = val; + } else if (cmp < 0) { + + if (!root->left) + root->left = map_new_from_parent(root); + + map_insert(root->left, key, val); + } else if (cmp > 0) { + if (!root->right) + root->right = map_new_from_parent(root); + + map_insert(root->right, key, val); + } else { + return -1; + } + + return 0; +} + void map_clear(root) map *root; { diff --git a/collections/map/map.h b/collections/map/map.h index 11a1ceb..b389d87 100644 --- a/collections/map/map.h +++ b/collections/map/map.h @@ -10,6 +10,9 @@ map* map_new(cmp_func); /*management*/ int map_size(map*); +/*data*/ +int map_insert(map*, void*, void*); + /*memory*/ void map_clear(map*); void map_free(map*); -- cgit v1.1