aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTucker Evans <tucker@tuckerevans.com>2020-07-08 11:15:18 -0400
committerTucker Evans <tucker@tuckerevans.com>2020-07-08 11:15:18 -0400
commit78fa3e40d3c2f0d302f4779ca35352f5f68fba0b (patch)
treec240ee4f32a8aad69baa1b784d8242e4601620d7
parent1ec57ef8df39b2ad7af98e2e65d93a60e7851586 (diff)
Fix map insert error returns
Makes inserting an equivalent key an error, set_val should be used.
-rw-r--r--collections/map/map.adoc15
-rw-r--r--collections/map/map.c14
2 files changed, 15 insertions, 14 deletions
diff --git a/collections/map/map.adoc b/collections/map/map.adoc
index da0ebaf..27278b8 100644
--- a/collections/map/map.adoc
+++ b/collections/map/map.adoc
@@ -73,11 +73,9 @@ 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.
+Inserts a new item +value+ for +key+ into +self+
+This returns an int indicating a successful insertion; providing a NULL +self+
+or a key that is already in +self+ will return -1 otherwise 0 is returned.
Examples
^^^^^^^^
@@ -85,11 +83,14 @@ Examples
----
#include "map.h"
#include <string.h>
+#include <stdio.h>
map *dict = map_new((cmp_func) strcmp);
-map_insert(dict, "ONE", NULL);
-assert(map_size(dict) == 1);
+if (map_insert(dict, "ONE", NULL) < 0)
+ printf("Failed to insert {\"ONE\": NULL}\n");
+else
+ assert(map_size(dict) == 1);
----
[[map_reset_key]]
diff --git a/collections/map/map.c b/collections/map/map.c
index b21ed32..62cb016 100644
--- a/collections/map/map.c
+++ b/collections/map/map.c
@@ -82,24 +82,24 @@ void *key, *val;
cmp = root->cmp(root->key, key);
- if (cmp == 0 && root->key == key) {
- root->val = val;
- } else if (cmp < 0) {
+ if (cmp < 0) {
if (!root->left)
root->left = map_new_from_parent(root);
map_insert(root->left, key, val);
- } else if (cmp > 0) {
+ return 0;
+ }
+
+ if (cmp > 0) {
if (!root->right)
root->right = map_new_from_parent(root);
map_insert(root->right, key, val);
- } else {
- return -1;
+ return 0;
}
- return 0;
+ return -1;
}
void* map_reset_key(root, key)