Implementation of HashMap_ForEach with function pointers

This commit is contained in:
VegOwOtenks 2025-01-12 21:30:20 +01:00
parent 3d6f7a2957
commit a569dd05a6
2 changed files with 36 additions and 9 deletions

View file

@ -18,6 +18,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "hashmap.h"
#include <stdlib.h>
// ! Caution with value_size if you care to store something else than pointers
@ -353,6 +354,29 @@ int HashMap_EntryByIndex(hashmap_t* restrict hashmap, size_t index, hashmapentry
return EXIT_SUCCESS;
}
int HashMap_ForEach(hashmap_t* hashmap, HashMapVisitFunction visitor, void* context)
{
if (hashmap == NULL) {
return EINVAL;
}
if (visitor == NULL) {
return EINVAL;
}
for (size_t i = 0; i < hashmap->capacity; i++) {
hashmapentry_t* entry = hashmap->buckets[i];
while (entry != NULL) {
int visit_code = visitor(context, entry->key, entry->key_length, entry->value);
if (visit_code != EXIT_SUCCESS) {
return visit_code;
}
entry = entry->next;
}
}
return EXIT_SUCCESS;
}
size_t HashMap_Size(hashmap_t* restrict hashmap)
{
return hashmap->used;

View file

@ -48,20 +48,23 @@ typedef struct HashMap {
struct HashMapConfig config;
} hashmap_t;
typedef int (*HashMapVisitFunction) (void* context, void* key, size_t key_length, void* value);
struct HashMapConfig HashMap_DefaultConfig(void);
int HashMap_Create(hashmap_t* restrict destination, struct HashMapConfig* restrict config, size_t initial_capacity);
void HashMap_Destroy(hashmap_t* restrict hashmap);
int HashMap_Create(hashmap_t* destination, struct HashMapConfig* config, size_t initial_capacity);
void HashMap_Destroy(hashmap_t* hashmap);
int HashMap_Put(hashmap_t* restrict hashmap, const void* key, size_t key_length, void* value);
int HashMap_Remove(hashmap_t* restrict hashmap, const void* restrict key, size_t key_length);
int HashMap_Put(hashmap_t* hashmap, const void* key, size_t key_length, void* value);
int HashMap_Remove(hashmap_t* hashmap, const void* key, size_t key_length);
int HashMap_Get(hashmap_t* restrict hashmap, const void* key, size_t key_length, void* value_storage);
int HashMap_Get(hashmap_t* hashmap, const void* key, size_t key_length, void* value_storage);
int HashMap_Update(hashmap_t* restrict hashmap, const void* key, size_t key_length, void* new_value);
int HashMap_Update(hashmap_t* hashmap, const void* key, size_t key_length, void* new_value);
int HashMap_ValueByIndex(hashmap_t* restrict hashmap, size_t index, void* store_here);
int HashMap_EntryByIndex(hashmap_t* restrict hashmap, size_t index, hashmapentry_t** store_here);
size_t HashMap_Size(hashmap_t* restrict hashmap);
int HashMap_ValueByIndex(hashmap_t* hashmap, size_t index, void* store_here);
int HashMap_EntryByIndex(hashmap_t* hashmap, size_t index, hashmapentry_t** store_here);
int HashMap_ForEach(hashmap_t* hashmap, HashMapVisitFunction visitor, void* context);
size_t HashMap_Size(hashmap_t* hashmap);
#endif /* SRC_COMMON_HASHMAP_HASHMAP_H_ */