From 68a62ad356603d64d537e231f06b5d9445e79abe Mon Sep 17 00:00:00 2001 From: kartofen Date: Fri, 23 Aug 2024 19:55:13 +0300 Subject: usefull commit message --- src/hashtable.h | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/hashtable.h (limited to 'src/hashtable.h') diff --git a/src/hashtable.h b/src/hashtable.h new file mode 100644 index 0000000..b9b1b2a --- /dev/null +++ b/src/hashtable.h @@ -0,0 +1,54 @@ +#ifndef HASHMAP_H +#define HASHMAP_H + +#include + +typedef struct hashtable *hashtable_t; + +typedef size_t (*hashtable_hash_func)(void *key); +typedef bool (*hashtable_equal_func)(void *key1, void *key2); + +struct hashtable { + hashtable_hash_func hash_func; + hashtable_equal_func equal_func; + + struct hashtable_item { + struct hashtable_item *next; + void *key; + void *data; + } **table; + + size_t size; + size_t cap; +}; + +hashtable_t hashtable_create(size_t cap, hashtable_hash_func hash_func, hashtable_equal_func equal_func); +void hashtable_destroy(hashtable_t ht); +void hashtable_reset(hashtable_t ht); + +int hashtable_insert(hashtable_t ht, void *key, void *data, + void **prevkey, void **prevdata); +int hashtable_query(hashtable_t ht, void *key, void **data); +int hashtable_delete(hashtable_t ht, void *key); + +#define hashtable_for_each_item(ht, item, i) \ + for(size_t i = 0; i < ht->cap; i++) \ + for(struct hashtable_item *item = ht->table[i]; \ + item != NULL; \ + item = item->next) + +#define hashtable_for_each_item_on_index(ht, item, idx) \ + for(struct hashtable_item *item = \ + ht->table[idx]; \ + item != NULL; \ + item = item->next) + +#define hashtable_for_each_item_safe(ht, item, i) \ + for(size_t i = 0; i < ht->cap; i++) \ + for(struct hashtable_item \ + *item = ht->table[i], \ + *next = NULL; \ + item != NULL && (next = item->next, 1); \ + item = next) + +#endif -- cgit v1.2.3