nserver

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | LICENSE

commit fde085c87b6c30eeb6181921b3e9b13ee295700c
parent 5c129f9684a474c8d162aa639e8f2e6dc9c1a807
Author: rsiddharth <s@ricketyspace.net>
Date:   Sat,  9 Nov 2019 10:24:43 -0500

nserver: Update hashmap.

Add missing functions from lcthw/hashmap.

Diffstat:
nserver/src/hashmap.c | 49+++++++++++++++++++++++++++++++++++++++++++++++++
nserver/src/hashmap.h | 1+
2 files changed, 50 insertions(+), 0 deletions(-)

diff --git a/nserver/src/hashmap.c b/nserver/src/hashmap.c @@ -34,6 +34,26 @@ static uint32_t default_hash(void *a) return hash; } +/** + * Fucked up version of FNV hash + */ +uint32_t fnv_hash(void *a) +{ + size_t len = blength((bstring) a); + char *key = bdata((bstring) a); + uint32_t hash = 0; + uint32_t i = 0; + uint32_t fnv_prime = 16777619; + uint32_t fnv_offset_basis = 2166136261; + + hash = fnv_offset_basis; + for (i = 0; i < len; ++i) { + hash *= fnv_prime; + hash ^= key[i]; + } + + return hash; +} Hashmap *Hashmap_create(Hashmap_compare compare, Hashmap_hash hash) { @@ -197,6 +217,35 @@ void *Hashmap_get(Hashmap *map, void *key) return NULL; } +/** + * Sets key <-> data iff key is not already present in Hashmap. + */ +int Hashmap_set_fucked(Hashmap *map, void *key, void *data) +{ + uint32_t hash = 0; + DArray *bucket = Hashmap_find_bucket(map, key, 1, &hash); + check(bucket, "Error can't create bucket"); + + int i = Hashmap_get_node(map, hash, bucket, key); + if (i >= 0) { + // Element with `key` already exists. Do nothing. + return 0; + } + + // Element with `key` does not exist. Add it to Hashmap. + HashmapNode *node = Hashmap_node_create(hash, key, data); + check_mem(node); + + DArray_push(bucket, node); + + // Sort the bucket. + int rc = DArray_heapsort(bucket, (DArray_compare) map->compare); + check(rc == 0, "Error sorting bucket"); + + return 1; + error: + return -1; +} int Hashmap_traverse(Hashmap *map, Hashmap_traverse_cb traverse_cb) { diff --git a/nserver/src/hashmap.h b/nserver/src/hashmap.h @@ -29,6 +29,7 @@ Hashmap *Hashmap_create(Hashmap_compare, Hashmap_hash); void Hashmap_destroy(Hashmap *map); int Hashmap_set(Hashmap *map, void *key, void *data); +int Hashmap_set_fucked(Hashmap *map, void *key, void *data); void *Hashmap_get(Hashmap *map, void *key); int Hashmap_traverse(Hashmap *map, Hashmap_traverse_cb travers_cb);