start implementing string functions

Tue, 30 Aug 2022 19:56:07 +0200

author
Mike Becker <universe@uap-core.de>
date
Tue, 30 Aug 2022 19:56:07 +0200
changeset 579
bbc46dcd5255
parent 578
0b2c0cb280a9
child 580
aac47db8da0b

start implementing string functions

src/string.c file | annotate | diff | comparison | revisions
--- a/src/string.c	Tue Aug 30 19:55:56 2022 +0200
+++ b/src/string.c	Tue Aug 30 19:56:07 2022 +0200
@@ -27,3 +27,103 @@
  */
 
 #include "cx/string.h"
+#include "cx/utils.h"
+
+#include <string.h>
+#include <stdarg.h>
+#include <stdint.h>
+
+cxmutstr cx_mutstr(char *cstring) {
+    return (cxmutstr) {cstring, strlen(cstring)};
+}
+
+cxmutstr cx_mutstrn(
+        char *cstring,
+        size_t length
+) {
+    return (cxmutstr) {cstring, length};
+}
+
+cxstring cx_str(const char *cstring) {
+    return (cxstring) {cstring, strlen(cstring)};
+}
+
+cxstring cx_strn(
+        const char *cstring,
+        size_t length
+) {
+    return (cxstring) {cstring, length};
+}
+
+cxstring cx_strcast(cxmutstr str) {
+    return (cxstring) {str.ptr, str.length};
+}
+
+void cx_strfree(cxmutstr *str) {
+    free(str->ptr);
+    str->ptr = NULL;
+    str->length = 0;
+}
+
+size_t cx_strlen(
+        size_t count,
+        ...
+) {
+    if (count == 0) return 0;
+
+    va_list ap;
+    va_start(ap, count);
+    size_t size = 0;
+    cx_for_n(i, count) {
+        cxstring str = va_arg(ap, cxstring);
+        size += str.length;
+    }
+    va_end(ap);
+
+    return size;
+}
+
+cxmutstr cx_strcat_a(
+        CxAllocator *alloc,
+        size_t count,
+        ...
+) {
+    cxstring *strings = calloc(count, sizeof(cxstring));
+    if (!strings) abort();
+
+    va_list ap;
+    va_start(ap, count);
+
+    // get all args and overall length
+    size_t slen = 0;
+    cx_for_n(i, count) {
+        cxstring s = va_arg (ap, cxstring);
+        strings[i] = s;
+        slen += s.length;
+    }
+
+    // create new string
+    cxmutstr result;
+    result.ptr = cxMalloc(alloc, slen + 1);
+    result.length = slen;
+    if (result.ptr == NULL) abort();
+
+    // concatenate strings
+    size_t pos = 0;
+    cx_for_n(i, count) {
+        cxstring s = strings[i];
+        memcpy(result.ptr + pos, s.ptr, s.length);
+        pos += s.length;
+    }
+
+    // terminate string
+    result.ptr[result.length] = '\0';
+
+    // free temporary array
+    free(strings);
+
+    return result;
+}
+
+
+

mercurial