-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap.c
More file actions
70 lines (56 loc) · 1.44 KB
/
map.c
File metadata and controls
70 lines (56 loc) · 1.44 KB
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
/**
* map.c
*
* A custum unordered map implementation using hash_table universal hashing for
* the confidential inference project.
*
* Author: Haoling Zhou
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "map.h"
//#define DEBUG
#define PRIME 101
#define A 53
#define B 79
int hash(char *key, int key_len, int table_size) {
int key_val = 0;
for (int i = 0; i < key_len; i++) {
key_val += key[i];
}
return ((A * key_val + B) % PRIME) % table_size;
}
void insert(chain_node *node, map *ht) {
int idx = hash(node->key, strlen(node->key), ht->size);
#ifdef DEBUG
printf("node key: %s\n", node->key);
printf("hash value: %d\n", idx);
#endif
if (idx < 0 || idx >= ht->size) {
printf("Error: idx out of bound\n");
exit(EXIT_FAILURE);
}
if (ht->lists[idx]->head == NULL) {
ht->lists[idx]->head = node;
} else {
chain_node *tmp = ht->lists[idx]->head;
ht->lists[idx]->head = node;
node->next = tmp;
tmp->prev = node;
}
#ifdef DEBUG
printf("New head node key: %s\n", ht->lists[idx]->head->key);
if (ht->lists[idx]->head->next != NULL)
printf("Old head node key: %s\n", ht->lists[idx]->head->next->key);
#endif
}
void *search(char *key, map *ht) {
int idx = hash(key, strlen(key), ht->size);
chain_node *cur = ht->lists[idx]->head;
while (strcmp(key, cur->key) != 0 && cur != NULL)
cur = cur->next;
if (cur == NULL)
return NULL;
return cur->val;
}