-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcosql_kv.c
More file actions
61 lines (51 loc) · 1008 Bytes
/
cosql_kv.c
File metadata and controls
61 lines (51 loc) · 1008 Bytes
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
#include<string.h>
#include<stdlib.h>
#include "cosql_kv.h"
hash_table* init()
{
hash_table* tab;
tab = (hash_table*)malloc(sizeof(hash_table));
int i;
for(i = 0; i < TABLE_SIZE; i++)
tab->nodes[i] = NULL;
return tab;
}
void destroy(hash_table *tab)
{
int i; for(i = 0; i < TABLE_SIZE; i++)
{
if(tab->nodes[i])
{
free(tab->nodes[i]->key);
free(tab->nodes[i]);
}
}
free(tab);
tab = NULL;
}
int add(hash_table* tab,char* k, int v)
{
int hash = hash_func(k);
if(tab->nodes[hash] == NULL)
tab->nodes[hash] = malloc(sizeof(node));
else return 1;
tab->nodes[hash]->key = (char*)malloc(sizeof(char) * (strlen(k) + 1));
strcpy(tab->nodes[hash]->key,k);
tab->nodes[hash]->value = v;
return 0;
}
int find(hash_table* tab,char* key)
{
int hash = hash_func(key);
if(tab->nodes[hash] != NULL)
return tab->nodes[hash]->value;
else return -1;
}
unsigned int hash_func(char* k)
{
unsigned int hash = 1;
char* c;
for(c = k; *c; c++)
hash = *c+hash*31;
return hash % TABLE_SIZE;
}