aboutsummaryrefslogtreecommitdiff
path: root/collections
diff options
context:
space:
mode:
Diffstat (limited to 'collections')
-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)