aboutsummaryrefslogtreecommitdiff
path: root/smash/variables.c
blob: b3b6689d47b6c5ea91df68b32c8665b4fcad6645 (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
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
#include "variables.h"

#include "../lib/avl_tree/avl_tree.h"
#include "../lib/cstr/cstr.h"
#include "../lib/malloc/malloc.h"

typedef struct {
	const char *name;
	const char *value;
} variable_pair_t;

i8   __variable_pair_compare(void *a, void *b);

avl_tree_t *variable_tree;


/** DOC
 * @type function
 * @name __variable_pair_compare
 *
 * @param  void *a
 * @param  void *b
 * @return u8
 *
 * @description
 * Compair function for `variable_pair_t`.
 */
i8 __variable_pair_compare(void *a, void *b)
{
	variable_pair_t *va = (variable_pair_t*)a;
	variable_pair_t *vb = (variable_pair_t*)b;

	return cstr_compare(va->name, vb->name);
}


/** DOC
 * @type function
 * @name init_variables
 *
 * @description
 * Initializes the variable binary tree.
 */
void init_variables()
{
	variable_tree = new_avl_tree(__variable_pair_compare, 1);
}


/** DOC
 * @type function
 * @name set_variable
 *
 * @param const char *name
 * @param const char *value
 *
 * @description
 * Sets a variable.
 */
void set_variable(const char *name, const char *value)
{
	variable_pair_t *pair = malloc(sizeof(variable_pair_t));
	pair->name = name;
	pair->value = value;
	avl_tree_insert(variable_tree, pair);
}


/** DOC
 * @type function
 * @name get_variable
 *
 * @param const char *name
 *
 * @description
 * Gets a variable.
 */
const char *get_variable(const char *name)
{
	variable_pair_t query = { .name = name, .value = 0 };
	variable_pair_t *res = avl_tree_search(variable_tree, &query);

	if (res)
		return res->value;
	return 0;
}


#ifdef VARIABLES_UNIT_TEST

#include "../lib/sys/write.h"

void test_get(const char *name)
{
	const char *value = get_variable(name);
	if (value)
		write(0, value, cstr_length(value));
	else
		write(0, "value = nullptr", 15);
	
	write(0, "\n", 1);

}

int main()
{
	init_variables();
	set_variable("name", "john");
	set_variable("user", "n8");
	
	test_get("name");
	test_get("user");

	set_variable("user", "freak");
	
	test_get("user");

}

#endif