add single instance mode
[uwplayer.git] / ucx / string.c
index baca3a6..d4b7005 100644 (file)
@@ -72,7 +72,7 @@ void cx_strfree(cxmutstr *str) {
 }
 
 void cx_strfree_a(
-        CxAllocator *alloc,
+        CxAllocator const *alloc,
         cxmutstr *str
 ) {
     cxFree(alloc, str->ptr);
@@ -98,11 +98,14 @@ size_t cx_strlen(
     return size;
 }
 
-cxmutstr cx_strcat_a(
-        CxAllocator *alloc,
+cxmutstr cx_strcat_ma(
+        CxAllocator const *alloc,
+        cxmutstr str,
         size_t count,
         ...
 ) {
+    if (count == 0) return str;
+
     cxstring *strings = calloc(count, sizeof(cxstring));
     if (!strings) abort();
 
@@ -110,34 +113,38 @@ cxmutstr cx_strcat_a(
     va_start(ap, count);
 
     // get all args and overall length
-    size_t slen = 0;
+    size_t slen = str.length;
     cx_for_n(i, count) {
         cxstring s = va_arg (ap, cxstring);
         strings[i] = s;
         slen += s.length;
     }
+    va_end(ap);
 
-    // create new string
-    cxmutstr result;
-    result.ptr = cxMalloc(alloc, slen + 1);
-    result.length = slen;
-    if (result.ptr == NULL) abort();
+    // reallocate or create new string
+    if (str.ptr == NULL) {
+        str.ptr = cxMalloc(alloc, slen + 1);
+    } else {
+        str.ptr = cxRealloc(alloc, str.ptr, slen + 1);
+    }
+    if (str.ptr == NULL) abort();
 
     // concatenate strings
-    size_t pos = 0;
+    size_t pos = str.length;
+    str.length = slen;
     cx_for_n(i, count) {
         cxstring s = strings[i];
-        memcpy(result.ptr + pos, s.ptr, s.length);
+        memcpy(str.ptr + pos, s.ptr, s.length);
         pos += s.length;
     }
 
     // terminate string
-    result.ptr[result.length] = '\0';
+    str.ptr[str.length] = '\0';
 
     // free temporary array
     free(strings);
 
-    return result;
+    return str;
 }
 
 cxstring cx_strsubs(
@@ -369,7 +376,7 @@ size_t cx_strsplit(
 }
 
 size_t cx_strsplit_a(
-        CxAllocator *allocator,
+        CxAllocator const *allocator,
         cxstring string,
         cxstring delim,
         size_t limit,
@@ -411,7 +418,7 @@ size_t cx_strsplit_m(
 }
 
 size_t cx_strsplit_ma(
-        CxAllocator *allocator,
+        CxAllocator const *allocator,
         cxmutstr string,
         cxstring delim,
         size_t limit,
@@ -470,7 +477,7 @@ int cx_strcasecmp_p(
 }
 
 cxmutstr cx_strdup_a(
-        CxAllocator *allocator,
+        CxAllocator const *allocator,
         cxstring string
 ) {
     cxmutstr result = {
@@ -579,7 +586,7 @@ static void cx_strrepl_free_ibuf(struct cx_strreplace_ibuf *buf) {
 }
 
 cxmutstr cx_strreplacen_a(
-        CxAllocator *allocator,
+        CxAllocator const *allocator,
         cxstring str,
         cxstring pattern,
         cxstring replacement,