aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTucker Evans <tucker@tuckerevans.com>2020-07-06 19:47:22 -0400
committerTucker Evans <tucker@tuckerevans.com>2020-07-08 11:02:40 -0400
commit51d368c20e1d93970a94cb0d2aff10654922bb37 (patch)
tree2903118e96ca69a499e91e63c5ee6c217b47e44d
parent0cca188d0ccbfe3d87805c74b63fef72a58a2b84 (diff)
Add insert function for maps
-rw-r--r--collections/map/map.adoc24
-rw-r--r--collections/map/map.c37
-rw-r--r--collections/map/map.h3
3 files changed, 63 insertions, 1 deletions
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.
+<<reset_key,+map_reset_key()+>> can be used to fix this issue.
+
+Examples
+^^^^^^^^
+[source,c]
+----
+#include "map.h"
+#include <string.h>
+
+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*);