summaryrefslogtreecommitdiff
path: root/src/utils.c
blob: c828f8e5062baaf542a856a4a6dc8e0110bab8e6 (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
#include "utils.h"
#include <string.h>
#include <stdlib.h>

void append_str_to_String(String* target, const char* src_str) {
    size_t len = strlen(src_str);

    for (size_t i = 0; i < len; i++) {
        push_to_String(target, src_str[i]);
    }
}

char* inner(String* str) {
    char *out = malloc(str->count + 1);
    if (!out) abort();

    for (size_t i = 0; i < str->count; i++) {
        out[i] = *get_from_String(str, i);
    }

    out[str->count] = '\0';
    return out;
}


void set_map_pair(KeyValMap* map, StrPair pair) {
    for (int i = 0; i < map->count; i++) {
        char* key_i = get_from_KeyValMap(map, i)->key;
        if (key_i == NULL) continue;
        if (strcmp(key_i, pair.key) == 0) {
            // TODO: maybe copy instead
            strcpy(
                map->blocks[i / map->block_size][i % map->block_size].val,
                pair.val
            );
            return;
        }
    }
    push_to_KeyValMap(map, pair);
}

MaybeStr get_map_value(KeyValMap* map, char* key) {
    for (int i = 0; i < map->count; i++) {
        char* key_i = get_from_KeyValMap(map, i)->key;
        if (key_i == NULL) continue;
        if (strcmp(key_i, key) == 0) {
            return (MaybeStr){
                .some = true,
                .value = get_from_KeyValMap(map, i)->val
            };
        }
    }
    return (MaybeStr){.some = false};
} 

void unset_map_key(KeyValMap* map, char* key) {
    for (int i = 0; i < map->count; i++) {
        char* key_i = get_from_KeyValMap(map, i)->key;
        if (key_i == NULL) continue;
        if (strcmp(key_i, key) == 0) {
            map->blocks[i / map->block_size][i % map->block_size].key = NULL;
            break;
        }
    }
}


char* get_var(char* varname, ShellState* shstate) {
    MaybeStr maybe_varval = get_map_value(&shstate->shell_vars, varname); 
    if (maybe_varval.some == true) return maybe_varval.value;
    return getenv(varname);
}


bool is_identifier(char* str) {
    if (str == NULL) return false;
	if (!isalpha(str[0]) && str[0] != '_') return false;
for (int i = 1; str[i] != '\0'; i++) {
		if (!isalnum(str[i]) && str[i] != '_') return false;
	}
	return true;
}