diff options
author | Yaroslav de la Peña Smirnov <yps@yaroslavps.com> | 2021-11-05 19:45:02 +0300 |
---|---|---|
committer | Yaroslav de la Peña Smirnov <yps@yaroslavps.com> | 2021-11-05 19:45:02 +0300 |
commit | 975465c3f5302117eef779672ada76627371c3bf (patch) | |
tree | 25e47f898ff4a2c3177e1979febc269ed4e719fd /src/hashmap.h | |
parent | a986818ad798d50f41d9e1fd569c926a67341b6e (diff) | |
download | unja-975465c3f5302117eef779672ada76627371c3bf.tar.gz unja-975465c3f5302117eef779672ada76627371c3bf.zip |
Hashmap improvements and include guards
Hashmap capacity can be set programmatically and it grows/shrinks in
size when the load increases/decreases to avoid collisions/save memory.
Diffstat (limited to 'src/hashmap.h')
-rw-r--r-- | src/hashmap.h | 49 |
1 files changed, 41 insertions, 8 deletions
diff --git a/src/hashmap.h b/src/hashmap.h index dbb45da..5a1e22d 100644 --- a/src/hashmap.h +++ b/src/hashmap.h @@ -1,13 +1,46 @@ -#define HASHMAP_CAP 26 +#ifndef UNJA_HASHMAP_H +#define UNJA_HASHMAP_H +#include <stdbool.h> +#include <sys/types.h> + +#ifndef HASHMAP_CAP +#define HASHMAP_CAP 32 +#endif + +#ifndef HASHMAP_MIN_LOAD +#define HASHMAP_MIN_LOAD 0.2 +#endif + +#ifndef HASHMAP_MAX_LOAD +#define HASHMAP_MAX_LOAD 0.75 +#endif + +#ifndef HASHMAP_GROW_RATE +#define HASHMAP_GROW_RATE 2 +#endif struct hashmap { - struct node *buckets[HASHMAP_CAP]; + struct node **buckets; + size_t init_cap; + size_t cur_cap; + size_t size; }; -struct hashmap *hashmap_new(); -void *hashmap_insert(struct hashmap *hm, char *key, void *value); -void *hashmap_get(struct hashmap *hm, char *key); -void *hashmap_resolve(struct hashmap *hm, char *key); -void *hashmap_remove(struct hashmap *hm, char *key); +/* allocate a new hashmap */ +struct hashmap *hashmap_new_with_cap(size_t cap); + +#define hashmap_new() hashmap_new_with_cap(HASHMAP_CAP) + +void *hashmap_insert(struct hashmap *hm, const char *key, void *value); + +void *hashmap_get(struct hashmap *hm, const char *key); + +void *hashmap_resolve(struct hashmap *hm, const char *key); + +void *hashmap_remove(struct hashmap *hm, const char *key); + void hashmap_free(struct hashmap *hm); -void hashmap_walk(struct hashmap *hm, void (*fn)(void *value));
\ No newline at end of file + +void hashmap_walk(struct hashmap *hm, void (*fn)(void *value)); + +#endif |