-
Notifications
You must be signed in to change notification settings - Fork 0
/
dict.c
47 lines (40 loc) · 1.05 KB
/
dict.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
#include <stdlib.h>
#include <stddef.h>
#include <inttypes.h>
#include "vec.h"
#include "dict.h"
#include "util.h"
dict_t *dict_new(size_t size){
return vec_new(size);
}
dict_entry_t *dict_get_entry(dict_t *dict, uintptr_t key){
for(int i = 0; i < vec_length(dict); i++){
dict_entry_t *e = vec_get(dict, i);
if(e->key == key) return e;
}
return NULL;
}
dict_entry_t *dict_get_or_create_entry(dict_t *dict, uintptr_t key){
dict_entry_t *e = dict_get_entry(dict, key);
if(e == NULL){
e = malloc(sizeof(dict_entry_t));
e->key = key;
e->value = NULL;
vec_push(dict, e);
}
return e;
}
void *dict_get(dict_t *dict, uintptr_t key){
dict_entry_t *e = dict_get_entry(dict, key);
if(e) return e->value;
return NULL;
}
void *dict_put(dict_t *dict, uintptr_t key, void *value){
dict_entry_t *e = dict_get_or_create_entry(dict, key);
void *tmp = e->value;
e->value = value;
return tmp;
}
dict_entry_t *dict_elem(dict_t *dict, size_t idx){
return vec_get(dict, idx);
}