blob: 0dd8a04b704d564b378f4110bc12afe7ffb4336c [file] [log] [blame]
Damien429d7192013-10-04 19:53:11 +01001#include <assert.h>
2#include <string.h>
3
4#include "misc.h"
5
6static int qstrs_alloc;
7static int qstrs_len;
8static const char **qstrs;
9
Damien8b3a7c22013-10-23 20:20:17 +010010void qstr_init(void) {
Damien429d7192013-10-04 19:53:11 +010011 qstrs_alloc = 400;
12 qstrs_len = 1;
13 qstrs = m_new(const char*, qstrs_alloc);
14 qstrs[0] = "nil";
15}
16
17static qstr qstr_add(const char *str) {
18 if (qstrs_len >= qstrs_alloc) {
Damien732407f2013-12-29 19:33:23 +000019 qstrs = m_renew(const char*, qstrs, qstrs_alloc, qstrs_alloc * 2);
Damien429d7192013-10-04 19:53:11 +010020 qstrs_alloc *= 2;
Damien429d7192013-10-04 19:53:11 +010021 }
22 qstrs[qstrs_len++] = str;
23 return qstrs_len - 1;
24}
25
26qstr qstr_from_str_static(const char *str) {
27 for (int i = 0; i < qstrs_len; i++) {
28 if (strcmp(qstrs[i], str) == 0) {
29 return i;
30 }
31 }
32 return qstr_add(str);
33}
34
Damien732407f2013-12-29 19:33:23 +000035qstr qstr_from_str_take(char *str, int alloc_len) {
Damien429d7192013-10-04 19:53:11 +010036 for (int i = 0; i < qstrs_len; i++) {
37 if (strcmp(qstrs[i], str) == 0) {
Damien732407f2013-12-29 19:33:23 +000038 m_del(char, str, alloc_len);
Damien429d7192013-10-04 19:53:11 +010039 return i;
40 }
41 }
42 return qstr_add(str);
43}
44
45qstr qstr_from_strn_copy(const char *str, int len) {
46 for (int i = 0; i < qstrs_len; i++) {
47 if (strncmp(qstrs[i], str, len) == 0 && qstrs[i][len] == '\0') {
48 return i;
49 }
50 }
51 return qstr_add(strndup(str, len));
52}
53
54const char *qstr_str(qstr qstr) {
55 return qstrs[qstr];
56}