-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenv.c
127 lines (94 loc) · 2.5 KB
/
env.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "env.h"
#include <sys/queue.h>
struct env_entry;
typedef TAILQ_HEAD(environment, env_entry) environment_t;
typedef struct env_entry env_entry_t;
struct env_entry {
env_pair_t env_pair;
TAILQ_ENTRY(env_entry) entries;
};
static environment_t _environment;
static env_entry_t *_env_entry_get(const char *symbol);
void
env_init(void)
{
TAILQ_INIT(&_environment);
}
void
env_deinit(void)
{
env_entry_t *env_np;
env_np = TAILQ_FIRST(&_environment);
while (env_np != NULL) {
env_entry_t * const next =
TAILQ_NEXT(env_np, entries);
if (env_np->env_pair.symbol != NULL) {
free((void *)env_np->env_pair.symbol);
}
free(env_np);
env_np = next;
}
}
void
env_put(const char *symbol, void *value)
{
assert(symbol != NULL);
env_entry_t *env_entry;
env_entry = _env_entry_get(symbol);
if (env_entry != NULL) {
env_entry->env_pair.value = value;
} else {
env_entry = malloc(sizeof(env_entry_t));
assert(env_entry != NULL);
env_entry->env_pair.symbol = strdup(symbol);
env_entry->env_pair.value = value;
TAILQ_INSERT_TAIL(&_environment, env_entry, entries);
}
}
bool
env_get(const char *symbol, env_pair_t *pair)
{
assert(symbol != NULL);
assert(pair != NULL);
env_entry_t * const env_entry = _env_entry_get(symbol);
pair->symbol = symbol;
pair->value = NULL;
if (env_entry == NULL) {
return false;
}
*pair = env_entry->env_pair;
return true;
}
void *
env_value_get(const char *symbol)
{
env_pair_t pair;
if (!(env_get(symbol, &pair))) {
return NULL;
}
return pair.value;
}
void
env_traverse(env_traverse_func_t func)
{
assert(func != NULL);
env_entry_t *env_np;
TAILQ_FOREACH (env_np, &_environment, entries) {
func(&env_np->env_pair);
}
}
static env_entry_t *
_env_entry_get(const char *symbol)
{
env_entry_t *env_np;
TAILQ_FOREACH (env_np, &_environment, entries) {
if ((strcmp(symbol, env_np->env_pair.symbol)) == 0) {
return env_np;
}
}
return NULL;
}