From 20c79049e9b0a6a1aa47b1b9dacfbb31b6e7c992 Mon Sep 17 00:00:00 2001 From: Tucker Evans Date: Mon, 6 Jul 2020 17:26:10 -0400 Subject: Add clear & free functions for maps --- collections/map/map.adoc | 48 +++++++++++++++++++++++++++++++++++++++++++++++- collections/map/map.c | 44 ++++++++++++++++++++++++++++++++++++++++++++ collections/map/map.h | 3 +++ 3 files changed, 94 insertions(+), 1 deletion(-) 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 <> should be called immediatly after this. + +Examples +^^^^^^^^ +[source,c] +---- +#include "map.h" +#include + +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 +<>, <> 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 -- cgit v1.1