From 6a564da0f9c510c0222b05ba5da18c6ef73e8030 Mon Sep 17 00:00:00 2001 From: leo Date: Wed, 3 Apr 2024 15:16:39 -0300 Subject: map implementado --- map.c | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 map.c (limited to 'map.c') diff --git a/map.c b/map.c new file mode 100644 index 0000000..58ed548 --- /dev/null +++ b/map.c @@ -0,0 +1,77 @@ +#include "include/map.h" +#include +#include +string_map init_map(uint32_t size){ + string_map tmp; + + tmp.size = size; + tmp.head = (node **)malloc(sizeof(node *) * size); + + node **h = tmp.head; + for(int i = 0; i < size; ++i){ + h[i] = NULL; + } + + return tmp; +} + +/* + * 64-bit FNV-1 hash + * https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function + */ +uint32_t hash_function(char *key, uint32_t size){ + uint64_t hash = FNV_offset_basis; + uint32_t key_size = strlen(key); + + for(int i = 0; i < key_size; ++i){ + hash *= FNV_prime; + hash ^= (uint64_t)key[i]; + } + + return hash % size; +} + +node *create_node(char *key, char *value){ + node *tmp = (node *)malloc(sizeof(node)); + tmp->key = key; + tmp->value = value; + tmp->next = NULL; + return tmp; +} + +void insert_map(char *key, char *value, string_map map){ + uint32_t hash_offset = hash_function(key, map.size); + + if(*(map.head + hash_offset) == NULL){ + node *tmp = create_node(key, value); + *(map.head + hash_offset) = tmp; + return; + } + + node *head = *(map.head + hash_offset); + while(head->next != NULL){ + if(strcmp(key, (head->key)) == 0){ + printf("REPETIDO\n"); + return; + } + head = head->next; + } + + node *tmp = create_node(key, value); + (head->next) = tmp; +} + +char *get_value(char *key, string_map map){ + uint32_t hash_offset = hash_function(key, map.size); + node *head = *(map.head + hash_offset); + + while(head != NULL){ + if(strcmp(key, (head->key)) == 0){ + return head->value; + } + head = head->next; + } + + fprintf(stderr, "VALOR NAO ESTA NO HASH TABLE\n"); + return NULL; +} -- cgit v1.2.3