-
Notifications
You must be signed in to change notification settings - Fork 0
/
dmap.c
70 lines (59 loc) · 1.47 KB
/
dmap.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
/*
* Copyright Ted Meyer 2015
*
* see LICENSE for details
*
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "dmap.h"
struct map *map_init(unsigned int size) {
struct map *result = calloc(sizeof(struct map), 1);
result->body = calloc(sizeof(struct kvp**), size);
result->size = size;
return result;
}
unsigned int hash(char *key) {
unsigned int result = 0;
while(*key) {
result += *key;
key++;
}
return result;
}
void *put(struct map *map, char *key, void *val) {
unsigned int h = hash(key);
struct kvpl *c_list = (map->body)[h % map->size];
struct kvpl *c_temp = c_list;
while(c_temp) {
if (strcmp(key, c_temp->kvp->key)==0) {
void *old = c_temp->kvp->val;
c_temp->kvp->val = val;
return old;
}
c_temp = c_temp->next;
}
struct kvp *new = malloc(sizeof(struct kvp));
new->key = key;
new->val = val;
struct kvpl *newl = malloc(sizeof(struct kvpl));
newl->kvp = new;
newl->next = c_list;
(map->body)[h % map->size] = c_list = newl;
return NULL;
}
void *get(struct map *map, char *key) {
unsigned int h = hash(key);
struct kvpl *c_temp = (map->body)[h % map->size];
while(c_temp) {
if (strcmp(key, c_temp->kvp->key)==0) {
return c_temp->kvp->val;
}
c_temp = c_temp->next;
}
return NULL;
}
struct map *map_new() {
return map_init(DEFAULT_SIZE);
}