blob: 10aa65128997b35a32bacc14a6836889ade8f8f3 (
plain)
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
|
#include <stdlib.h>
#include <string.h>
#include "common.h"
#include "env.h"
#include "value.h"
#define ENV_TABLE_CAP (1 << 8)
static unsigned long str_hash(char *str)
{
unsigned long hash = 5381;
int c;
while ((c = *str++))
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash;
}
static size_t hash(void *key)
{
return str_hash((char*)key);
}
static bool equal(void *key1, void *key2)
{
if(strcmp((char *)key1, (char*)key2) == 0) {
return true;
}
return false;
}
env_t env_create(env_t parent, env_destroy_func destroy_func)
{
env_t env = malloc(sizeof(*env));
env->destroy_func = destroy_func;
env->parent = parent;
env->refs = 1;
ERR_Z(env->table = hashtable_create(ENV_TABLE_CAP, hash, equal),
env_destroy(env));
return env;
}
void env_destroy(env_t env)
{
if(!env) return;
env->refs--;
env_destroy(env->parent);
if(env->refs > 0) return;
hashtable_for_each_item(env->table, item, i) {
env->destroy_func((char *)item->key, (value_t)item->data);
}
hashtable_destroy(env->table);
free(env);
}
env_t env_copy(env_t env)
{
if(env == ENV_EMPTY) return ENV_EMPTY;
env->refs++;
env_copy(env->parent);
return env;
}
|