-
Notifications
You must be signed in to change notification settings - Fork 8
/
string.c
71 lines (63 loc) · 1.49 KB
/
string.c
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
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include "8cc.h"
#define INIT_SIZE 8
String *make_string(void) {
String *r = malloc(sizeof(String));
r->body = malloc(INIT_SIZE);
r->nalloc = INIT_SIZE;
r->len = 0;
r->body[0] = '\0';
return r;
}
static void realloc_body(String *s) {
int newsize = s->nalloc * 2;
char *body = malloc(newsize);
strcpy(body, s->body);
s->body = body;
s->nalloc = newsize;
}
char *get_cstring(String *s) {
return s->body;
}
int string_len(String *s) {
return s->len;
}
void string_append(String *s, char c) {
if (s->nalloc == (s->len + 1))
realloc_body(s);
s->body[s->len++] = c;
s->body[s->len] = '\0';
}
void string_appendf(String *s, char *fmt, ...) {
va_list args;
for (;;) {
int avail = s->nalloc - s->len;
va_start(args, fmt);
int written = vsnprintf(s->body + s->len, avail, fmt, args);
va_end(args);
if (avail <= written) {
realloc_body(s);
continue;
}
s->len += written;
return;
}
}
char *format(char *fmt, ...) {
String *s = make_string();
va_list args;
for (;;) {
int avail = s->nalloc - s->len;
va_start(args, fmt);
int written = vsnprintf(s->body + s->len, avail, fmt, args);
va_end(args);
if (avail <= written) {
realloc_body(s);
continue;
}
s->len += written;
return get_cstring(s);
}
}