ref: f97663aa375e4220ca9c78f4b3215e987384dfac
parent: 08bdbd1949ee356acbc3f218f47bc8918ef4eff3
author: Jakub Kądziołka <[email protected]>
date: Fri Apr 16 09:08:14 EDT 2021
hashmap: add hash_GetNode
--- a/include/hashmap.h
+++ b/include/hashmap.h
@@ -52,6 +52,14 @@
bool hash_RemoveElement(HashMap map, char const *key);
/**
+ * Finds an element in a hashmap, and returns a pointer to its value field.
+ * @param map The map to consider the elements of
+ * @param key The key to search an element for
+ * @return A pointer to the pointer to the element, or NULL if not found.
+ */
+void **hash_GetNode(HashMap const map, char const *key);
+
+/**
* Finds an element in a hashmap.
* @param map The map to consider the elements of
* @param key The key to search an element for
--- a/src/hashmap.c
+++ b/src/hashmap.c
@@ -66,18 +66,14 @@
bool hash_ReplaceElement(HashMap const map, char const *key, void *element)
{
- HashType hashedKey = hash(key);
- struct HashMapEntry *ptr = map[(HalfHashType)hashedKey];
+ void **node = hash_GetNode(map, key);
- while (ptr) {
- if (hashedKey >> HALF_HASH_NB_BITS == ptr->hash
- && !strcmp(ptr->key, key)) {
- ptr->content = element;
- return true;
- }
- ptr = ptr->next;
+ if (node) {
+ *node = element;
+ return true;
+ } else {
+ return false;
}
- return false;
}
bool hash_RemoveElement(HashMap map, char const *key)
@@ -99,7 +95,7 @@
return false;
}
-void *hash_GetElement(HashMap const map, char const *key)
+void **hash_GetNode(HashMap const map, char const *key)
{
HashType hashedKey = hash(key);
struct HashMapEntry *ptr = map[(HalfHashType)hashedKey];
@@ -107,11 +103,18 @@
while (ptr) {
if (hashedKey >> HALF_HASH_NB_BITS == ptr->hash
&& !strcmp(ptr->key, key)) {
- return ptr->content;
+ return &ptr->content;
}
ptr = ptr->next;
}
return NULL;
+}
+
+void *hash_GetElement(HashMap const map, char const *key)
+{
+ void **node = hash_GetNode(map, key);
+
+ return node ? *node : NULL;
}
void hash_ForEach(HashMap const map, void (*func)(void *, void *), void *arg)