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.c | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) (limited to 'collections/map/map.c') 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; { -- cgit v1.1