summaryrefslogtreecommitdiffstatshomepage
path: root/py/qstr.c
blob: 0dd8a04b704d564b378f4110bc12afe7ffb4336c (plain) (blame)
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
#include <assert.h>
#include <string.h>

#include "misc.h"

static int qstrs_alloc;
static int qstrs_len;
static const char **qstrs;

void qstr_init(void) {
    qstrs_alloc = 400;
    qstrs_len = 1;
    qstrs = m_new(const char*, qstrs_alloc);
    qstrs[0] = "nil";
}

static qstr qstr_add(const char *str) {
    if (qstrs_len >= qstrs_alloc) {
        qstrs = m_renew(const char*, qstrs, qstrs_alloc, qstrs_alloc * 2);
        qstrs_alloc *= 2;
    }
    qstrs[qstrs_len++] = str;
    return qstrs_len - 1;
}

qstr qstr_from_str_static(const char *str) {
    for (int i = 0; i < qstrs_len; i++) {
        if (strcmp(qstrs[i], str) == 0) {
            return i;
        }
    }
    return qstr_add(str);
}

qstr qstr_from_str_take(char *str, int alloc_len) {
    for (int i = 0; i < qstrs_len; i++) {
        if (strcmp(qstrs[i], str) == 0) {
            m_del(char, str, alloc_len);
            return i;
        }
    }
    return qstr_add(str);
}

qstr qstr_from_strn_copy(const char *str, int len) {
    for (int i = 0; i < qstrs_len; i++) {
        if (strncmp(qstrs[i], str, len) == 0 && qstrs[i][len] == '\0') {
            return i;
        }
    }
    return qstr_add(strndup(str, len));
}

const char *qstr_str(qstr qstr) {
    return qstrs[qstr];
}