summaryrefslogtreecommitdiff
path: root/src/resources/config.c
blob: 05b80cde0ab11d083125a9bdb936cc6c8b49bc2d (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
#include "resources.h"
#include <stdlib.h>
#include <stddef.h>
#include <raylib.h>
#include <stdio.h>
#include <string.h>

Config config = {
    .MaxOperations = DEFAULT_MAX_OPS,
};

bool startsWith(const char *str, const char *prefix) {
    if (str == NULL || prefix == NULL) {
        return false;
    }

    size_t prefix_len = strlen(prefix);

    if (strlen(str) < prefix_len) {
        return false;
    }

    return strncmp(str, prefix, prefix_len) == 0;
}

// Strips everything before '=' (including). Does not allocate.
char *stripName(char *line, size_t len) {
    if (line == NULL) {
        return NULL;
    }
    
    for (size_t ptr = 0; ptr < len; ptr++) {
        if (line[ptr] == '\0') {
            return NULL; 
        }
        if (line[ptr] == '=') {
            return &line[ptr + 1];
        }
    }

    return NULL;
}

// Reads one line and assigns the param if found
void evaluateConfigLive(char *line) {
    size_t len = strlen(line);
    // Empty lines and comments
    if (len <= 1 || line[0] == '#') return;
    // Removing a new line
    if (line[len-1] == '\n') {
        line[len-1] = 0x0;
        len -= 1;
    }

    if (startsWith(line, "MaxOperations")) {
        char *value = stripName(line, len);

        char *endptr;
        unsigned long long parsed = strtoull(value, &endptr, 10);
        if (value == endptr || *endptr != '\0') {
            TraceLog(LOG_WARNING, "Failed to parse the value for MaxOperations. Provided value: '%s'", value); 
            return;
        }
        config.MaxOperations = parsed;
        return;
    }

}

bool ReadConfig(const char *location) {
    FILE *file = fopen(location, "r");
    if (file == NULL) {
        perror("Failed to open the config file");
        return false;
    }

    fseek(file, 0, SEEK_END);
    long size = ftell(file);
    rewind(file);

    char* buffer = malloc(size + 1);
    if (buffer == NULL) {
        fclose(file);
        perror("Failed to load the config file");
        return false;
    }


    while (fgets(buffer, size, file)) {
        evaluateConfigLive(buffer);
    }

    free(buffer);
    fclose(file);
    return true;
}

Config *GetConfig() {
    return &config;
}