From 456b8fc754e4fb63ab25913910b4c42f06d43b75 Mon Sep 17 00:00:00 2001 From: Tyge Løvset <60263450+tylo-work@users.noreply.github.com> Date: Mon, 9 Mar 2020 00:58:42 +0100 Subject: added cstring_makeTemp --- cmap_test.c | 3 +++ cstring.h | 14 +++++++++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/cmap_test.c b/cmap_test.c index 3db1252f..fcb138b7 100644 --- a/cmap_test.c +++ b/cmap_test.c @@ -91,6 +91,9 @@ int main() stringSpeed(20000); + CString tmp = cstring_makeTemp("I will automatically be destroyed when going out of scope"); + printf("tmp: %s\n", tmp.str); + CString cs = cstring_make("one-nine-three-seven-five"); printf("%s.\n", cs.str); cstring_insert(&cs, 3, "-two"); diff --git a/cstring.h b/cstring.h index 42f2ea76..b6529528 100644 --- a/cstring.h +++ b/cstring.h @@ -43,16 +43,24 @@ static size_t _cstring_null_rep[] = {0, 0, 0}; #define cstring_size(cs) ((size_t) _cstring_rep(cs)[0]) #define cstring_capacity(cs) ((size_t) _cstring_rep(cs)[1]) #define cstring_npos ((size_t) -1) +#define cstring_makeTemp(str) _cstring_makeTemp(str, (size_t *) alloca(2 * sizeof(size_t) + strlen(str) + 1)) +static inline CString _cstring_makeTemp(const char* str, size_t *rep) { + CString cs = {(char *) (rep + 2)}; + strcpy(cs.str, str); + rep[0] = strlen(str); + rep[1] = 0; // no cap -> no destroy. OK + return cs; +} + static inline void cstring_reserve(CString* self, size_t cap) { size_t len = cstring_size(*self), oldcap = cstring_capacity(*self); if (cap > oldcap) { size_t* rep = (size_t *) realloc(oldcap ? _cstring_rep(*self) : NULL, sizeof(size_t) * 2 + cap + 1); - rep[0] = len; - rep[1] = cap; self->str = (char* ) (rep + 2); - self->str[len] = '\0'; + self->str[ rep[0] = len ] = '\0'; + rep[1] = cap; } } -- cgit v1.2.3