summaryrefslogtreecommitdiff
path: root/source/base/base_parse.c
blob: 4f216bfbebc6cf7e7543f1f65614a52c8d740a23 (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
/*
 * is_numeric - Check if a string contains only digits
 * @s: String to check
 *
 * Return: 1 if string contains only numeric characters, 0 otherwise
 */
internal b8
is_numeric(char *s)
{
    for (; *s; ++s)
    {
        if (*s < '0' || *s > '9')
        {
            return 0;
        }
    }
    return 1;
}

/*
 * TODO(nasr): checkout i think there is a buffer overflow happening somewhere
 * */
internal proc_file *
parse_proc_files(char *path, mem_arena *arena)
{
    if (!path || !arena)
    {
        return NULL;
    }

    i32 fd = open(path, O_RDONLY);
    if (fd < 0)
    {
        return NULL;
    }

    char *buffer = PushArray(arena, char, KiB(4));
    u64   bytes  = read(fd, buffer, KiB(4));
    close(fd);

    if (bytes == 0)
    {
        return NULL;
    }

    /* guessing the count to 256 because i dont want to do a double pass of the buffer */
    proc_file *pf = PushStruct(arena, proc_file);
    pf->entries   = PushArray(arena, proc_entry, 256);

    u64 line_start  = 0;
    u64 delim       = -1;
    u64 entry_index = 0;

    for (u64 index = 0; index < bytes; ++index)
    {
        if (buffer[index] == ':' && delim == (u64)-1)
        {
            delim = index;
        }
        else if (buffer[index] == '\n')
        {
            if (delim != (-1.f))
            {
                u64 key_len = delim - line_start;
                if (key_len >= sizeof(pf->entries[entry_index].key))
                {
                    key_len = sizeof(pf->entries[entry_index].key) - 1;
                }

                u64 val_start = delim + 1;
                while (val_start < index && (buffer[val_start] == ' ' || buffer[val_start] == '\t'))
                {
                    val_start++;
                }

                u64 val_len = index - val_start;
                if (val_len >= sizeof(pf->entries[entry_index].value))
                {
                    val_len = sizeof(pf->entries[entry_index].value) - 1;
                }

                MemCpy(pf->entries[entry_index].key, buffer + line_start, key_len - 1);
                MemCpy(pf->entries[entry_index].value, buffer + val_start, val_len);

                pf->entries[entry_index].key[key_len]   = '\0';
                pf->entries[entry_index].value[val_len] = '\0';

                ++pf->count;
                ++entry_index;
            }

            line_start = index + 1;
            delim      = (u64)-1;
        }
    }

    return (pf);
}