diff options
| author | Tyge Løvset <[email protected]> | 2020-03-09 00:58:42 +0100 |
|---|---|---|
| committer | GitHub <[email protected]> | 2020-03-09 00:58:42 +0100 |
| commit | 456b8fc754e4fb63ab25913910b4c42f06d43b75 (patch) | |
| tree | 55ecaa2ba623346cbff475e7e1f6526328499d57 | |
| parent | de99eca6d86ee2e05c85fb7793f8a737811abce6 (diff) | |
| download | STC-modified-456b8fc754e4fb63ab25913910b4c42f06d43b75.tar.gz STC-modified-456b8fc754e4fb63ab25913910b4c42f06d43b75.zip | |
added cstring_makeTemp
| -rw-r--r-- | cmap_test.c | 3 | ||||
| -rw-r--r-- | 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");
@@ -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;
}
}
|
