#include #include #include #include "finalize.h" #include "str.h" enum { MIN_CAPACITY = 8 }; void releaseStr(const struct Str *str) { free((char *)(uintptr_t)str->cstr); } void clearStr(struct Str *str) { if (str->capacity == 0) { str->end = str->cstr = malloc(MIN_CAPACITY); if (!str->cstr) { fprintf(stderr, "clearStr: out of memory\n"); finalizeExit(1); } str->capacity = MIN_CAPACITY; } *(str->end = str->cstr) = 0; } void appendCharToStr(struct Str *str, char c) { size_t len = str->end - str->cstr; // length without terminating 0 // check if another character and 0 byte fits into string if (len + 2 > str->capacity) { str->capacity = len + 2; if (str->capacity < MIN_CAPACITY) { str->capacity = MIN_CAPACITY; } else { str->capacity *= 2; } str->cstr = realloc(str->cstr, str->capacity); if (!str->cstr) { fprintf(stderr, "appendCharToStr: out of memory\n"); finalizeExit(1); } str->end = str->cstr + len; } *str->end++ = c; *str->end = 0; }