hydroforth/src/hydroforth/hashmap.c
2023-08-04 21:42:01 +02:00

67 lines
1.6 KiB
C

#include <stdlib.h>
#include "hydroforth/hydroforth.h"
static inline size_t hashvalue(const hf__hash_t hash, const size_t size) {
return hash % size;
}
void hf__hashmap__insert(struct hf__hashmap *const hashmap,
const hf__hash_t hash, void *value) {
struct hf__hashmap__node **const node =
hashmap->arr + hashvalue(hash, hashmap->cap);
if (*node == NULL) {
*node = malloc(sizeof(struct hf__hashmap__node));
(**node) = (struct hf__hashmap__node){
.hash = hash,
.value = value,
.next = NULL,
};
} else {
struct hf__hashmap__node *new_node = *node;
while (new_node->next) {
new_node = new_node->next;
}
new_node->next = malloc(sizeof(struct hf__hashmap__node));
*new_node->next = (struct hf__hashmap__node){
.hash = hash,
.value = value,
.next = NULL,
};
}
}
void **hf__hashmap__get(const struct hf__hashmap *const hashmap,
const hf__hash_t hash) {
struct hf__hashmap__node *node = hashmap->arr[hashvalue(hash, hashmap->cap)];
if (node == NULL) {
return NULL;
}
while (node->hash != hash) {
node = node->next;
if (node == NULL) {
return NULL;
}
}
return &node->value;
}
void hf__hashmap__free(struct hf__hashmap *const hashmap,
const hf__hashmap__free_value_t free_value) {
for (size_t i = 0; i < hashmap->cap; i++) {
struct hf__hashmap__node *node = hashmap->arr[i];
while (node != NULL) {
if (free_value) {
free_value(node->value);
}
struct hf__hashmap__node *next = node->next;
free(node);
node = next;
}
}
}