#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