-
Notifications
You must be signed in to change notification settings - Fork 2
/
map.c
115 lines (86 loc) · 1.81 KB
/
map.c
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include "map.h"
#include "queue.h"
#include "defs.h"
#define BUCKET_CAPACITY 256
struct entry {
const void* key;
void* value;
};
typedef struct link {
struct link* next;
struct entry e;
} *link_t;
struct map {
link_t buckets[BUCKET_CAPACITY];
int size;
};
map_t map_create()
{
map_t m = (void*)kalloc();
memset(m, 0, 4096);
m->size = 0;
return m;
}
void map_put(map_t m, const void* key, void* value, int (*hash)(const void*), int (*equal)(const void*, const void*))
{
if(m == 0) {
return;
}
int h = hash(key);
int pos = h % BUCKET_CAPACITY;
if(m->buckets[pos] != 0) {
link_t ptr = m->buckets[pos];
while(ptr != 0) {
if(equal(ptr->e.key, key)){
ptr->e.value = value;
return;
}
ptr = ptr->next;
}
}
link_t lk = (void*)kalloc();
struct entry e = {.key = key, .value = value};
lk->next = m->buckets[pos];
lk->e = e;
m->buckets[pos] = lk;
m->size++;
}
void* map_get(map_t m, const void* key, int (*hash)(const void*), int (*equal)(const void*, const void*))
{
if(m == 0) {
return 0;
}
int h = hash(key);
int pos = h % BUCKET_CAPACITY;
link_t ptr = m->buckets[pos];
while(ptr != 0) {
if(equal(ptr->e.key, key)) {
return ptr->e.value;
}
}
return 0;
}
int map_size(map_t m)
{
if(m == 0) {
return 0;
}
return m->size;
}
void map_keys(map_t m, const void** buffer)
{
if(m == 0) {
*buffer = 0;
return;
}
int pos = 0;
for(int i = 0; i < BUCKET_CAPACITY; i++)
{
link_t ptr = m->buckets[i];
while(ptr != 0) {
buffer[pos] = ptr->e.key;
pos++;
ptr = ptr->next;
}
}
}