From: alex Date: Wed, 8 Sep 2021 18:59:11 +0000 (-0700) Subject: ... X-Git-Url: http://git.infiniteadaptability.org/?a=commitdiff_plain;h=8e3ac4db42c601291521edb2a685087ac854fafa;p=seeder ... --- diff --git a/Makefile.am b/Makefile.am index fbc11a2..f95f2c2 100644 --- a/Makefile.am +++ b/Makefile.am @@ -15,6 +15,7 @@ seederd_SOURCES = \ src/add.c \ src/default.c \ src/file.c \ + src/hashmap.c \ src/log.c \ src/main.c \ src/opt/config.c \ @@ -36,6 +37,7 @@ seederd_SOURCES += \ inc/add.h \ inc/default.h \ inc/file.h \ + inc/hashmap.h \ inc/log.h \ inc/main.h \ inc/opt.h \ diff --git a/inc/hashmap.h b/inc/hashmap.h new file mode 100644 index 0000000..ab1ab37 --- /dev/null +++ b/inc/hashmap.h @@ -0,0 +1,18 @@ +#ifndef __HASHMAP_H_ +#define __HASHMAP_H_ + +#include + +struct hash_map { + void **map; + size_t size; + unsigned char key[crypto_shorthash_KEYBYTES]; +}; + +void *hashmap_find(struct hash_map*,void*,size_t); +void hashmap_free(struct hash_map*); +int hashmap_init(struct hash_map**,size_t); +int hashmap_insert(struct hash_map*,void*,size_t,void*); +void *hashmap_remove(struct hash_map*,void*,size_t); + +#endif diff --git a/src/hashmap.c b/src/hashmap.c new file mode 100644 index 0000000..0f38931 --- /dev/null +++ b/src/hashmap.c @@ -0,0 +1,73 @@ +#include + +void *hashmap_find(struct hash_map *p, void *key, size_t key_size) { + unsigned char hash[crypto_shorthash_KEYBYTES]; + size_t index; + + if(crypto_shorthash(hash,key,key_size,p->key)<0) { return NULL; } + + index = ((uint64_t) hash)%p->size; + return p->map[index]; +} + +void hashmap_free(struct hash_map *p) { + for(size_t i=0;isize;i++) { + if(p->map[i]!=NULL) { free(p->map[i]); } + } + + if(p->map!=NULL) { free(p->map); } + free(p); +} + +int hashmap_init(struct hash_map **p, size_t initial_size) { + if(sodium_init()<0) { + perror("sodium_init"); + return -1; + } + + *p = malloc(sizeof(struct hash_map)); + if(NULL==(*p)) { + perror("malloc"); + return -1; + } + + (*p)->map = malloc(sizeof(void*)*initial_size); + (*p)->size = initial_size; + + for(size_t i=0;imap[i] = NULL; + } + + crypto_shorthash_keygen((*p)->key); + + return 1; +} + +int hashmap_insert(struct hash_map *p, void *key, size_t key_size, void *value) { + unsigned char hash[crypto_shorthash_KEYBYTES]; + size_t index; + + if(crypto_shorthash(hash,key,key_size,p->key)<0) { return -1; } + + index = ((uint64_t) hash)%p->size; + if(p->map[index]!=NULL) { return 0; } + + p->map[index] = value; + + return 1; +} + +void *hashmap_remove(struct hash_map *p, void *key, size_t key_size) { + unsigned char hash[crypto_shorthash_KEYBYTES]; + size_t index; + void *removed; + + if(crypto_shorthash(hash,key,key_size,p->key)<0) { return NULL; } + + index = ((uint64_t) hash)%p->size; + removed = p->map[index]; + + p->map[index] = NULL; + + return removed; +}