Implement expanding hashmap
This commit is contained in:
parent
99347fd433
commit
5d9c971060
1 changed files with 23 additions and 2 deletions
25
hmap.c
25
hmap.c
|
@ -66,9 +66,12 @@ typedef struct _map_node hmap_node;
|
|||
typedef struct {
|
||||
size_t capacity;
|
||||
size_t len;
|
||||
size_t keysize;
|
||||
hmap_node *buckets;
|
||||
} hmap;
|
||||
|
||||
hmap_node* hmap_insert(hmap * map, void *key, size_t keysize, void *data);
|
||||
|
||||
hmap_node* hmap_node_init(void *key, size_t keysize, void *data) {
|
||||
hmap_node *node;
|
||||
uint64_t hash;
|
||||
|
@ -101,14 +104,15 @@ void* hmap_node_attach(hmap_node *root, hmap_node *leaf) {
|
|||
// todo
|
||||
}
|
||||
|
||||
hmap* hmap_init() {
|
||||
hmap* hmap_init(size_t keysize) {
|
||||
hmap* map;
|
||||
|
||||
map = calloc(1, sizeof(hmap));
|
||||
if (map == NULL) return NULL;
|
||||
map->len = 0;
|
||||
map->capacity = 64;
|
||||
map->buckets = calloc(64, sizeof(size_t));
|
||||
map->keysize = keysize;
|
||||
map->buckets = calloc(64, sizeof(hmap_node));
|
||||
if (map->buckets == NULL) {
|
||||
free(map);
|
||||
return NULL;
|
||||
|
@ -117,6 +121,23 @@ hmap* hmap_init() {
|
|||
}
|
||||
|
||||
int hmap_expand(hmap *map) {
|
||||
hmap_node *old;
|
||||
hmap_node *new;
|
||||
hmap_node *current;
|
||||
int i;
|
||||
|
||||
new = calloc(map->capacity + 64, sizeof(hmap_node));
|
||||
if (new == NULL) return 1;
|
||||
old = map->buckets;
|
||||
map->buckets = new;
|
||||
for (i = 0; i < map->capacity; i++) {
|
||||
current = &old[i];
|
||||
while (current->key != NULL) {
|
||||
hmap_insert(map, current->key, map->keysize, current->data);
|
||||
current = current->next;
|
||||
}
|
||||
}
|
||||
free(old);
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
|
Loading…
Add table
Reference in a new issue