From aeced5737c8b8d87a794bbb9775dd2145c43cabc Mon Sep 17 00:00:00 2001 From: Tucker Evans Date: Wed, 8 Jul 2020 11:31:38 -0400 Subject: Add check key ptr for map to ease memory management of keys --- collections/map/map.adoc | 37 +++++++++++++++++++++++++++++++++---- collections/map/map.c | 19 +++++++++++++++++++ collections/map/map.h | 1 + 3 files changed, 53 insertions(+), 4 deletions(-) (limited to 'collections/map') diff --git a/collections/map/map.adoc b/collections/map/map.adoc index 695f763..ce4999b 100644 --- a/collections/map/map.adoc +++ b/collections/map/map.adoc @@ -96,8 +96,37 @@ else assert(map_size(dict) == 1); ---- -[[map_reset_key]] -+void* map_reset_key(map *self, vaid *key)+ +[[map_check_key_ptr]] ++int map_check_key_ptr(map *self, void *key)+ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +This is used to check the key pointer for equivalent keys. +It is provided to ease memory management, in combination with +<>. + +Examples +^^^^^^^^ +[source,c] +---- +#include "map.h" +#include + +char *eq_key2 + +map *dict = map_new((cmp_func) strcmp); + +map_insert(dict, strdup("ONE"), NULL); + +eq_key2 = strdup("ONE"); + +/*Want to free key1 for some reason*/ +if (!map_check_key_ptr(dict, eq_key2)) { + free(map_set_key(dict, eq_key2)); +} + +---- + +[[map_set_key]] ++void* map_set_key(map *self, void *key)+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This replaces an equivalent key with the one passed in, the key that is overwritten is return so the user can free it. @@ -113,12 +142,12 @@ map *dict = map_new((cmp_func) strcmp); map_insert(dict, strdup("ONE"), "VALUE"); assert(map_insert(dict, "ONE", "NEW_VALUE") < 0); -free(map_reset_key(dict "ONE")); +free(map_set_key(dict "ONE")); assert(map_insert(dict, "ONE", "NEW_VALUE") == 0); ---- [[map_index]] -+void* map_index(map *self, vaid *key)+ ++void* map_index(map *self, void *key)+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Returns the value associated with +key+ (or equivalent). diff --git a/collections/map/map.c b/collections/map/map.c index 00f2225..66382ba 100644 --- a/collections/map/map.c +++ b/collections/map/map.c @@ -102,6 +102,25 @@ void *key, *val; return -1; } +int map_check_key_ptr(root, key) +map *root; +void *key; +{ + int cmp; + + if (!root || !key) + return 0; + + cmp = root->cmp(root->key, key); + + if (cmp < 0) + return map_check_key_ptr(root->left, key); + if (cmp > 0) + return map_check_key_ptr(root->right, key); + + return root->key == key; +} + void* map_set_key(root, key) map *root; void *key; diff --git a/collections/map/map.h b/collections/map/map.h index 9de3ba1..38e3e11 100644 --- a/collections/map/map.h +++ b/collections/map/map.h @@ -14,6 +14,7 @@ int map_size(map*); int map_insert(map*, void*, void*); void* map_index(map*, void*); +int map_check_key_ptr(map*, void*); void* map_set_key(map*, void*); -- cgit v1.1