aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTucker Evans <tucker@tuckerevans.com>2020-07-06 17:26:10 -0400
committerTucker Evans <tucker@tuckerevans.com>2020-07-08 10:56:36 -0400
commit20c79049e9b0a6a1aa47b1b9dacfbb31b6e7c992 (patch)
tree761f68ac650e7f974c0a45c61e980ce0fbe9881c
parent50846316de122801e07511d4e3771a4561efa5ad (diff)
Add clear & free functions for maps
-rw-r--r--collections/map/map.adoc48
-rw-r--r--collections/map/map.c44
-rw-r--r--collections/map/map.h3
3 files changed, 94 insertions, 1 deletions
diff --git a/collections/map/map.adoc b/collections/map/map.adoc
index 837a08a..4668e0e 100644
--- a/collections/map/map.adoc
+++ b/collections/map/map.adoc
@@ -66,6 +66,52 @@ Examples
map *dict = map_new((cmp_func) strcmp);
assert(map_size(dict) == 0);
-map_set(dict, "ONE", NULL);
+map_insert(dict, "ONE", NULL);
assert(map_size(dict) == 1);
----
+
+[[map_clear]]
++void map_clear(map *self)+
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Free all elements within dict +self+, and sets dict to empty (size 0).
+
+NOTE: Does not free all internal memory of +self+ or +self+ itself, if this is
+desired <<map_free,+map_free()+>> should be called immediatly after this.
+
+Examples
+^^^^^^^^
+[source,c]
+----
+#include "map.h"
+#include <string.h>
+
+char *str1 = "ONE";
+char *str2 = "TWO";
+
+map *dict = map_new();
+map_insert(dict, str_dup(str1), NULL);
+map_insert(dict, str_dup(str2), NULL);
+
+map_clear(dict);
+assert(map_size(dict) == 0);
+map_free(dict);
+----
+
+[[map_free]]
++void map_free(map *self)+
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+Frees all internal memory and +self+.
+
+NOTE: All item pointers are still valid after a call to
+<<map_free,+map_free()+>>, <<map_clear,+map_clear()+>> should be called before
+if they are no longer needed to avoid memory leaks.
+
+Examples
+^^^^^^^^
+[source,c]
+----
+#include "map.h"
+
+map *dict = map_new();
+map_free(dict);
+----
diff --git a/collections/map/map.c b/collections/map/map.c
index 712a895..beb8f7f 100644
--- a/collections/map/map.c
+++ b/collections/map/map.c
@@ -34,3 +34,47 @@ map *root;
return map_size(root->left) + map_size(root->right) + 1;
}
+
+void map_clear(root)
+map *root;
+{
+ map *l, *r;
+
+ l = root->left;
+ r = root->right;
+
+ if (!root)
+ return;
+
+ if (root->parent) {
+ free(root->key);
+ root->key = NULL;
+
+ free(root->val);
+ root->val = NULL;
+
+ root->parent = NULL;
+
+ free(root);
+ }
+
+ map_clear(l);
+ map_clear(r);
+}
+
+void map_free(root)
+map *root;
+{
+ if (!root)
+ return;
+
+ root->key = NULL;
+
+ map_free(root->left);
+ root->left = NULL;
+
+ map_free(root->right);
+ root->right = NULL;
+
+ free(root);
+}
diff --git a/collections/map/map.h b/collections/map/map.h
index ef4b0c8..11a1ceb 100644
--- a/collections/map/map.h
+++ b/collections/map/map.h
@@ -10,4 +10,7 @@ map* map_new(cmp_func);
/*management*/
int map_size(map*);
+/*memory*/
+void map_clear(map*);
+void map_free(map*);
#endif