aboutsummaryrefslogtreecommitdiff
path: root/hashtable.h
blob: 6a555a4dd10cf0e15e590d59ddd1621320fc4c07 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#ifndef HASHTABLE_H_INCLUDED
#define HASHTABLE_H_INCLUDED

/* in order to get strdup(), this needs to be defined */
#define _BSD_SOURCE

#include <stdint.h>
#include <stdlib.h>
#include <string.h>

typedef struct list_node {
    const char *k;
    void *v;
    struct list_node *next;
} list_node_t;

typedef struct hash_table {
    list_node_t **t;
    size_t sz;
} hash_table_t;

uint32_t hash_str(const char *s);
list_node_t * list_add(list_node_t *head, const char *k, void *v);
list_node_t * list_remove(list_node_t *head, const char *k);
list_node_t * list_get(list_node_t *head, const char *k);
size_t list_length(list_node_t *head);

hash_table_t * hashtable_new(size_t size);
void hash_table_free(hash_table_t *ht);

static inline void hashtable_add(hash_table_t *ht, const char *name, void *c) {
    uint32_t h = hash_str(name) % ht->sz;
    ht->t[h] = list_add(ht->t[h], name, (void *)c);
} 

static inline void hashtable_remove(hash_table_t *ht, const char *name) {
    uint32_t h = hash_str(name) % ht->sz;
    ht->t[h] = list_remove(ht->t[h], name);
}

static inline void * hashtable_get(hash_table_t *ht, const char *name) {
    uint32_t h = hash_str(name) % ht->sz;
    list_node_t *n = list_get(ht->t[h], name);
    return n ? n->v : NULL;
}

#endif // HASHTABLE_H_INCLUDED