From e75d6f6b8f4512a5bbfecbfa8c17f0bb687e3d55 Mon Sep 17 00:00:00 2001 From: Preston Pan Date: Tue, 24 Dec 2024 21:11:06 -0800 Subject: first commit --- src/better_string.c | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/better_string.c (limited to 'src/better_string.c') diff --git a/src/better_string.c b/src/better_string.c new file mode 100644 index 0000000..4413f77 --- /dev/null +++ b/src/better_string.c @@ -0,0 +1,51 @@ +#include +#include +#include +#include + +string_t *init_string(const char *src) { + string_t *s = safe_calloc(1, sizeof(string_t)); + size_t len = src ? strlen(src) : DEFAULT_STR_SIZE; + size_t size = len * 2; + s->buf = safe_calloc(size, sizeof(char)); + s->buf[0] = '\0'; + + if (src) + strcpy(s->buf, src); + s->len = len; + s->size = size; + return s; +} + +void string_push(string_t *s, char c) { + if (s->len >= s->size - 2) { + s->size *= 2; + s->buf = safe_realloc(s->buf, s->size); + } + s->buf[s->len] = c; + s->len++; +} + +char string_pop(string_t *s) { + char c = s->buf[s->len]; + s->len--; + return c; +} + +void string_concat_const(string_t *s1, const char *s2) { + for (int i = 0; i < strlen(s2); i++) { + string_push(s1, s2[i]); + } +} + +void string_concat(string_t *s1, string_t *s2) { + for (int i = 0; i < s2->len; i++) { + string_push(s1, s2->buf[i]); + } +} + +void string_free(void *x) { + string_t *s = x; + free(s->buf); + free(s); +} -- cgit