sic

The sic programming language, compiler and tools (WIP)
Log | Files | Refs

commit 23be80cdbfceac075f9bc4f8744ec2f78b59fa67
parent a1e845c47167ea29751750f4fa73347f10d204c9
Author: citbl <citbl@citbl.org>
Date:   Wed, 13 May 2026 21:15:20 +1000

fixes for string

Diffstat:
Msrc/array.h | 30+++++++++++++++++++++++++++++-
Msrc/str.c | 17++---------------
2 files changed, 31 insertions(+), 16 deletions(-)

diff --git a/src/array.h b/src/array.h @@ -1,5 +1,7 @@ #pragma once -// array_push + +#include <stdio.h> + #define ARRAY_PUSH(dest, len, cap, item) \ do { \ size_t arr_newcap, arr_itemsize; \ @@ -24,3 +26,29 @@ (dest)[(len)++] = (item); \ } while (0) +// similar but with the +1 size check and null delimiter at the end! +#define STRING_PUSH(dest, len, cap, item) \ + do { \ + size_t arr_newcap, arr_itemsize; \ + void* arr_newptr; \ + if ((len) + 1 >= (cap)) { /* +1 */ \ + arr_newcap = (cap) == 0 ? 256 : (cap) * 2; \ + arr_itemsize = sizeof(*(dest)); \ + if (arr_newcap <= (cap) || arr_newcap > SIZE_MAX / arr_itemsize) { \ + fprintf(stderr, "array: capacity overflow (cap=%zu)\n", (size_t)(cap)); \ + exit(1); \ + } \ + \ + arr_newptr = realloc((dest), arr_newcap * arr_itemsize); \ + if (!arr_newptr) { \ + fprintf(stderr, "array: could not reallocate\n"); \ + exit(1); \ + } \ + (dest) = arr_newptr; \ + (cap) = arr_newcap; \ + } \ + \ + (dest)[(len)++] = (item); \ + (dest)[(len)] = '\0'; \ + } while (0) + diff --git a/src/str.c b/src/str.c @@ -1,21 +1,8 @@ #include <stdlib.h> #include "str.h" -#include "common.h" +#include "array.h" void str_append(Str* str, const char c) { - size_t new_cap; - char* s; - - if (str->len + 1 >= str->cap) { // + 1 for the \0 - new_cap = str->cap == 0 ? 32 : str->cap * 2; - check(new_cap <= str->cap || new_cap > SIZE_MAX, "could not reallocate string\n"); - s = realloc(str->value, new_cap * sizeof(char)); - check(s == NULL, "str_append: could not alloc string\n"); - str->cap = new_cap; - str->value = s; - } - - str->value[str->len++] = c; - str->value[str->len] = '\0'; // important! + STRING_PUSH(str->value, str->len, str->cap, c); }