-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring_builder.h
More file actions
57 lines (51 loc) · 1.62 KB
/
Copy pathstring_builder.h
File metadata and controls
57 lines (51 loc) · 1.62 KB
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
#include <stddef.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
typedef struct {
char* buffer;
size_t length;
size_t _capacity;
} StringBuilder;
static inline StringBuilder StringBuilder_new() {
return (StringBuilder){
.buffer = NULL,
.length = 0,
._capacity = 0,
};
};
static inline void StringBuilder_append(StringBuilder* const self, const char* text) {
size_t len = strlen(text);
if (self->length + len + 1 > self->_capacity) {
size_t new_capacity = self->_capacity == 0 ? 1 : self->_capacity * 2;
while (self->length + len + 1 > new_capacity) {
new_capacity *= 2;
}
self->_capacity = new_capacity;
self->buffer = (char*)realloc(self->buffer, sizeof(char) * self->_capacity);
}
memcpy(self->buffer + self->length, text, len);
self->length += len;
self->buffer[self->length] = '\0';
}
static inline void StringBuilder_appendf(StringBuilder* const self, const size_t buf_size, char* fmt, ...) {
va_list args;
va_start(args, fmt);
char* buf = (char*)calloc(buf_size, sizeof(char));
vsnprintf(buf, buf_size * sizeof(char), fmt, args);
va_end(args);
StringBuilder_append(self, buf);
}
static inline char* StringBuilder_to_string(const StringBuilder* const self) {
char* text = (char*)malloc(self->length + 1);
memcpy(text, self->buffer, self->length);
text[self->length] = '\0';
return text;
}
static inline void StringBuilder_clear(StringBuilder* const self) {
free(self->buffer);
self->buffer = NULL;
self->length = 0;
self->_capacity = 0;
}