ucx/string.c

changeset 20
db7d9860dbbd
child 24
e04822101291
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/ucx/string.c	Thu Jan 05 14:53:54 2012 +0100
@@ -0,0 +1,99 @@
+/*
+ * File:   sstring.c
+ * Author: olaf
+ *
+ * Created on 17. Juni 2010, 13:27
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+
+#include "string.h"
+
+sstr_t sstr (char *s) {
+    sstr_t string;
+    string.ptr = s;
+    string.length = strlen(s);
+    return string;
+}
+
+sstr_t sstrn (char *s, size_t n) {
+    sstr_t string;
+    string.ptr = s;
+    string.length = n;
+    return string;
+}
+
+size_t sstrnlen (size_t n, sstr_t s, ...) {
+    va_list ap;
+    size_t size = s.length;
+    va_start(ap, s);
+
+    for (int i=0;i<n-1;i++) {
+        sstr_t str = va_arg(ap, sstr_t);
+        size += str.length;
+    }
+
+    return size;
+}
+
+sstr_t sstrcat (sstr_t s, ...) {
+    va_list ap;
+    va_start(ap, s);
+    s.ptr[0] = 0;
+
+    sstr_t str = va_arg (ap, sstr_t);
+    while (str.ptr != NULL) {
+        s.ptr = strncat (s.ptr, str.ptr, s.length);
+        str = va_arg (ap, sstr_t);
+    }
+
+    return s;
+}
+
+sstr_t sstrncat (size_t n, sstr_t s, sstr_t c1, ...) {
+    va_list ap;
+    va_start(ap, c1);
+    s.ptr[0] = 0;
+
+    s.ptr = strncat (s.ptr, c1.ptr, s.length);
+    for (int i=0;i<n-1;i++) {
+        sstr_t str = va_arg (ap, sstr_t);
+        s.ptr = strncat (s.ptr, str.ptr, s.length);
+    }
+
+    return s;
+}
+
+sstr_t sstrsubs (sstr_t s, size_t start) {
+    return sstrsubsl (s, start, s.length-start);
+}
+
+sstr_t sstrsubsl (sstr_t s, size_t start, size_t length) {
+    sstr_t new_sstr;
+    if (start < 0 || start >= s.length || length < 0) {
+        return s;
+    }
+    if (length > s.length-start) {
+        length = s.length-start;
+    }
+    new_sstr.ptr = &s.ptr[start];
+    new_sstr.length = length;
+    return new_sstr;
+}
+
+int sstrcmp(sstr_t s1, sstr_t s2) {
+    return strncmp(s1.ptr, s2.ptr, s1.length>s2.length ? s2.length: s1.length);
+}
+
+sstr_t sstrdub(sstr_t s) {
+    sstr_t newstring;
+    newstring.ptr = malloc(s.length + 1);
+    newstring.length = s.length;
+    newstring.ptr[newstring.length] = 0;
+
+    memcpy(newstring.ptr, s.ptr, s.length);
+
+    return newstring;
+}

mercurial