+// Type for a variable-length, allocated string.
+typedef struct {
+ char *str; // pointer to allocated string
+ size_t size; // size of allocation
+ size_t len; // length of string, not including terminating zero
+} string_t;
+
+// Clear a string_t.
+local void string_clear(string_t *s) {
+ s->str[0] = 0;
+ s->len = 0;
+}
+
+// Initialize a string_t.
+local void string_init(string_t *s) {
+ s->size = 16;
+ s->str = malloc(s->size);
+ assert(s->str != NULL && "out of memory");
+ string_clear(s);
+}
+
+// Release the allocation of a string_t.
+local void string_free(string_t *s) {
+ free(s->str);
+ s->str = NULL;
+ s->size = 0;
+ s->len = 0;
+}
+
+// Save the results of printf with fmt and the subsequent argument list to s.
+// Each call appends to s. The allocated space for s is increased as needed.
+local void string_printf(string_t *s, char *fmt, ...) {
+ va_list ap;
+ va_start(ap, fmt);
+ size_t len = s->len;
+ int ret = vsnprintf(s->str + len, s->size - len, fmt, ap);
+ assert(ret >= 0 && "out of memory");
+ s->len += ret;
+ if (s->size < s->len + 1) {
+ do {
+ s->size <<= 1;
+ assert(s->size != 0 && "overflow");
+ } while (s->size < s->len + 1);
+ s->str = realloc(s->str, s->size);
+ assert(s->str != NULL && "out of memory");
+ vsnprintf(s->str + len, s->size - len, fmt, ap);
+ }
+ va_end(ap);
+}
+