blob: 56a83d9c5b619544171d575d96b278a2edd0a6de (
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
/*
* Nome: Leonardo Koosuke Azuma
* SO: Arch Linux x86_64
* Compilador: gcc (GCC) 13.2.1 20230801
*/
#include "include/map.h"
#include <stdlib.h>
#include <stdio.h>
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;
}
|