forked from rui314/8cc
-
Notifications
You must be signed in to change notification settings - Fork 1
/
dict.c
70 lines (60 loc) · 1.67 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright 2012 Rui Ueyama <[email protected]>
// This program is free software licensed under the MIT license.
#include <stdlib.h>
#include <string.h>
#include "dict.h"
typedef struct DictEntry {
char *key;
void *val;
} DictEntry;
void *make_dict(void *parent) {
Dict *r = malloc(sizeof(Dict));
r->list = make_list();
r->parent = parent;
return r;
}
void *dict_get(Dict *dict, char *key) {
for (; dict; dict = dict->parent) {
for (Iter *i = list_iter(dict->list); !iter_end(i);) {
DictEntry *e = iter_next(i);
if (!strcmp(key, e->key))
return e->val;
}
}
return NULL;
}
void dict_put(Dict *dict, char *key, void *val) {
DictEntry *e = malloc(sizeof(DictEntry));
e->key = key;
e->val = val;
list_unshift(dict->list, e);
}
void dict_remove(Dict *dict, char *key) {
List *list = make_list();
for (Iter *i = list_iter(dict->list); !iter_end(i);) {
DictEntry *e = iter_next(i);
if (strcmp(key, e->key))
list_push(list, e);
}
dict->list = list;
}
bool dict_empty(Dict *dict) {
return list_len(dict->list) == 0;
}
List *dict_keys(Dict *dict) {
List *r = make_list();
for (; dict; dict = dict->parent)
for (Iter *i = list_iter(dict->list); !iter_end(i);)
list_unshift(r, ((DictEntry *)iter_next(i))->key);
return r;
}
List *dict_values(Dict *dict) {
List *r = make_list();
for (; dict; dict = dict->parent)
for (Iter *i = list_iter(dict->list); !iter_end(i);)
list_unshift(r, ((DictEntry *)iter_next(i))->val);
return r;
}
void *dict_parent(Dict *dict) {
return dict->parent;
}