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
|
void fatal_error(const char* msg, ...) {
va_list args;
va_start(args, msg);
vfprintf(stderr, msg, args);
va_end(args);
fprintf(stderr, "\n");
exit(1);
}
#define unreachable() fatal_error("%s:%d: unreachable", __FILE__, __LINE__)
#define unimplemented() fatal_error("%s:%d: unimplemented", __FILE__, __LINE__)
BOOL str_ends_with(const char* s, const char* suffix) {
size_t l1 = strlen(s);
size_t l2 = strlen(suffix);
if (l1 < l2)
return FALSE;
return strcmp(s + l1 - l2, suffix) == 0;
}
struct StrBuilder {
size_t len;
size_t capacity;
char* buf;
};
typedef struct StrBuilder StrBuilder;
void strbuilder_init(StrBuilder* b) {
b->len = 0;
b->capacity = 16;
b->buf = calloc(b->capacity, sizeof(char));
}
// `size` must include a trailing null byte.
void strbuilder_reserve(StrBuilder* b, size_t size) {
if (size <= b->capacity)
return;
while (b->capacity < size) {
b->capacity *= 2;
}
b->buf = realloc(b->buf, b->capacity * sizeof(char));
memset(b->buf + b->len, 0, (b->capacity - b->len) * sizeof(char));
}
void strbuilder_append_char(StrBuilder* b, int c) {
strbuilder_reserve(b, b->len + 1 + 1);
b->buf[b->len++] = c;
}
struct StrArray {
size_t len;
size_t capacity;
const char** data;
};
typedef struct StrArray StrArray;
void strings_init(StrArray* strings) {
strings->len = 0;
strings->capacity = 32;
strings->data = calloc(strings->capacity, sizeof(const char*));
}
void strings_reserve(StrArray* strings, size_t size) {
if (size <= strings->capacity)
return;
while (strings->capacity < size) {
strings->capacity *= 2;
}
strings->data = realloc(strings->data, strings->capacity * sizeof(const char*));
memset(strings->data + strings->len, 0, (strings->capacity - strings->len) * sizeof(const char*));
}
int strings_push(StrArray* strings, const char* str) {
strings_reserve(strings, strings->len + 1);
strings->data[strings->len] = str;
return ++strings->len;
}
|