forked from cblach/nikola-v2gstack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap.c
66 lines (56 loc) · 1.21 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
#include "map.h"
int
mapinit(Map *map,
size_t elemsz,
size_t nbuckets,
size_t (*hash)(Key),
int (*cmp)(Key, Key))
{
map->hash = hash;
map->cmp = cmp;
map->elemsz = elemsz;
map->nbuckets = nbuckets;
map->buckets = calloc(nbuckets, sizeof(void *));
return map->buckets ? 0 : -1;
}
void *
mapinsert(Map *map,
Key k)
{
size_t h = map->hash(k) % map->nbuckets;
Bucket *b = malloc(sizeof(Bucket) + map->elemsz);
if (!b) { return NULL; }
b->k = k;
b->next = map->buckets[h];
map->buckets[h] = b;
return b->v;
}
void *
mapfind(Map *map,
Key k)
{
size_t h = map->hash(k) % map->nbuckets;
Bucket *b;
for (b = map->buckets[h]; b; b = b->next) {
if (map->cmp(k, b->k) == 0) { return b->v; }
}
return NULL;
}
void
mapremove(Map *map,
Key k)
{
size_t h = map->hash(k) % map->nbuckets;
Bucket *b, *p;
for (p = NULL, b = map->buckets[h]; b; p = b, b = b->next) {
if (map->cmp(k, b->k) == 0) {
if (p) {
p->next = b->next;
} else {
map->buckets[h] = b->next;
}
free(b);
return;
}
}
}