ucx/string.c

changeset 101
7b3a3130be44
parent 49
2f71f4ee247a
--- a/ucx/string.c	Thu Dec 12 20:01:43 2024 +0100
+++ b/ucx/string.c	Mon Jan 06 22:22:55 2025 +0100
@@ -25,19 +25,23 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  * POSSIBILITY OF SUCH DAMAGE.
  */
-
+#define CX_STR_IMPLEMENTATION
 #include "cx/string.h"
-#include "cx/utils.h"
 
 #include <string.h>
 #include <stdarg.h>
 #include <ctype.h>
-
-#ifndef _WIN32
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
+#include <float.h>
 
-#include <strings.h> // for strncasecmp()
-
-#endif // _WIN32
+#ifdef _WIN32
+#define cx_strcasecmp_impl _strnicmp
+#else
+#include <strings.h>
+#define cx_strcasecmp_impl strncasecmp
+#endif
 
 cxmutstr cx_mutstr(char *cstring) {
     return (cxmutstr) {cstring, strlen(cstring)};
@@ -61,11 +65,8 @@
     return (cxstring) {cstring, length};
 }
 
-cxstring cx_strcast(cxmutstr str) {
-    return (cxstring) {str.ptr, str.length};
-}
-
 void cx_strfree(cxmutstr *str) {
+    if (str == NULL) return;
     free(str->ptr);
     str->ptr = NULL;
     str->length = 0;
@@ -75,6 +76,7 @@
         const CxAllocator *alloc,
         cxmutstr *str
 ) {
+    if (str == NULL) return;
     cxFree(alloc, str->ptr);
     str->ptr = NULL;
     str->length = 0;
@@ -89,8 +91,9 @@
     va_list ap;
     va_start(ap, count);
     size_t size = 0;
-    cx_for_n(i, count) {
+    for (size_t i = 0; i < count; i++) {
         cxstring str = va_arg(ap, cxstring);
+        if (size > SIZE_MAX - str.length) errno = EOVERFLOW;
         size += str.length;
     }
     va_end(ap);
@@ -106,33 +109,59 @@
 ) {
     if (count == 0) return str;
 
-    cxstring *strings = calloc(count, sizeof(cxstring));
-    if (!strings) abort();
+    cxstring strings_stack[8];
+    cxstring *strings;
+    if (count > 8) {
+        strings = calloc(count, sizeof(cxstring));
+        if (strings == NULL) {
+            return (cxmutstr) {NULL, 0};
+        }
+    } else {
+        strings = strings_stack;
+    }
 
     va_list ap;
     va_start(ap, count);
 
     // get all args and overall length
+    bool overflow = false;
     size_t slen = str.length;
-    cx_for_n(i, count) {
+    for (size_t i = 0; i < count; i++) {
         cxstring s = va_arg (ap, cxstring);
         strings[i] = s;
+        if (slen > SIZE_MAX - str.length) overflow = true;
         slen += s.length;
     }
     va_end(ap);
 
+    // abort in case of overflow
+    if (overflow) {
+        errno = EOVERFLOW;
+        if (strings != strings_stack) {
+            free(strings);
+        }
+        return (cxmutstr) { NULL, 0 };
+    }
+
     // reallocate or create new string
+    char *newstr;
     if (str.ptr == NULL) {
-        str.ptr = cxMalloc(alloc, slen + 1);
+        newstr = cxMalloc(alloc, slen + 1);
     } else {
-        str.ptr = cxRealloc(alloc, str.ptr, slen + 1);
+        newstr = cxRealloc(alloc, str.ptr, slen + 1);
     }
-    if (str.ptr == NULL) abort();
+    if (newstr == NULL) {
+        if (strings != strings_stack) {
+            free(strings);
+        }
+        return (cxmutstr) {NULL, 0};
+    }
+    str.ptr = newstr;
 
     // concatenate strings
     size_t pos = str.length;
     str.length = slen;
-    cx_for_n(i, count) {
+    for (size_t i = 0; i < count; i++) {
         cxstring s = strings[i];
         memcpy(str.ptr + pos, s.ptr, s.length);
         pos += s.length;
@@ -142,7 +171,9 @@
     str.ptr[str.length] = '\0';
 
     // free temporary array
-    free(strings);
+    if (strings != strings_stack) {
+        free(strings);
+    }
 
     return str;
 }
@@ -193,7 +224,7 @@
 ) {
     chr = 0xFF & chr;
     // TODO: improve by comparing multiple bytes at once
-    cx_for_n(i, string.length) {
+    for (size_t i = 0; i < string.length; i++) {
         if (string.ptr[i] == chr) {
             return cx_strsubs(string, i);
         }
@@ -236,7 +267,7 @@
 #ifndef CX_STRSTR_SBO_SIZE
 #define CX_STRSTR_SBO_SIZE 512
 #endif
-unsigned const cx_strstr_sbo_size = CX_STRSTR_SBO_SIZE;
+const unsigned cx_strstr_sbo_size = CX_STRSTR_SBO_SIZE;
 
 cxstring cx_strstr(
         cxstring haystack,
@@ -434,10 +465,14 @@
         cxstring s2
 ) {
     if (s1.length == s2.length) {
-        return memcmp(s1.ptr, s2.ptr, s1.length);
+        return strncmp(s1.ptr, s2.ptr, s1.length);
     } else if (s1.length > s2.length) {
+        int r = strncmp(s1.ptr, s2.ptr, s2.length);
+        if (r != 0) return r;
         return 1;
     } else {
+        int r = strncmp(s1.ptr, s2.ptr, s1.length);
+        if (r != 0) return r;
         return -1;
     }
 }
@@ -447,14 +482,14 @@
         cxstring s2
 ) {
     if (s1.length == s2.length) {
-#ifdef _WIN32
-        return _strnicmp(s1.ptr, s2.ptr, s1.length);
-#else
-        return strncasecmp(s1.ptr, s2.ptr, s1.length);
-#endif
+        return cx_strcasecmp_impl(s1.ptr, s2.ptr, s1.length);
     } else if (s1.length > s2.length) {
+        int r = cx_strcasecmp_impl(s1.ptr, s2.ptr, s2.length);
+        if (r != 0) return r;
         return 1;
     } else {
+        int r = cx_strcasecmp_impl(s1.ptr, s2.ptr, s1.length);
+        if (r != 0) return r;
         return -1;
     }
 }
@@ -556,13 +591,13 @@
 }
 
 void cx_strlower(cxmutstr string) {
-    cx_for_n(i, string.length) {
+    for (size_t i = 0; i < string.length; i++) {
         string.ptr[i] = (char) tolower(string.ptr[i]);
     }
 }
 
 void cx_strupper(cxmutstr string) {
-    cx_for_n(i, string.length) {
+    for (size_t i = 0; i < string.length; i++) {
         string.ptr[i] = (char) toupper(string.ptr[i]);
     }
 }
@@ -748,7 +783,7 @@
 
     // if more delimiters are specified, check them now
     if (ctx->delim_more_count > 0) {
-        cx_for_n(i, ctx->delim_more_count) {
+        for (size_t i = 0; i < ctx->delim_more_count; i++) {
             cxstring d = cx_strstr(haystack, ctx->delim_more[i]);
             if (d.length > 0 && (delim.length == 0 || d.ptr < delim.ptr)) {
                 delim.ptr = d.ptr;
@@ -784,3 +819,370 @@
     ctx->delim_more = delim;
     ctx->delim_more_count = count;
 }
+
+#define cx_strtoX_signed_impl(rtype, rmin, rmax) \
+    long long result; \
+    if (cx_strtoll_lc(str, &result, base, groupsep)) { \
+        return -1; \
+    } \
+    if (result < rmin || result > rmax) { \
+        errno = ERANGE; \
+        return -1; \
+    } \
+    *output = (rtype) result; \
+    return 0
+
+int cx_strtos_lc(cxstring str, short *output, int base, const char *groupsep) {
+    cx_strtoX_signed_impl(short, SHRT_MIN, SHRT_MAX);
+}
+
+int cx_strtoi_lc(cxstring str, int *output, int base, const char *groupsep) {
+    cx_strtoX_signed_impl(int, INT_MIN, INT_MAX);
+}
+
+int cx_strtol_lc(cxstring str, long *output, int base, const char *groupsep) {
+    cx_strtoX_signed_impl(long, LONG_MIN, LONG_MAX);
+}
+
+int cx_strtoll_lc(cxstring str, long long *output, int base, const char *groupsep) {
+    // strategy: parse as unsigned, check range, negate if required
+    bool neg = false;
+    size_t start_unsigned = 0;
+
+    // trim already, to search for a sign character
+    str = cx_strtrim(str);
+    if (str.length == 0) {
+        errno = EINVAL;
+        return -1;
+    }
+
+    // test if we have a negative sign character
+    if (str.ptr[start_unsigned] == '-') {
+        neg = true;
+        start_unsigned++;
+        // must not be followed by positive sign character
+        if (str.length == 1 || str.ptr[start_unsigned] == '+') {
+            errno = EINVAL;
+            return -1;
+        }
+    }
+
+    // now parse the number with strtoull
+    unsigned long long v;
+    cxstring ustr = start_unsigned == 0 ? str
+        : cx_strn(str.ptr + start_unsigned, str.length - start_unsigned);
+    int ret = cx_strtoull_lc(ustr, &v, base, groupsep);
+    if (ret != 0) return ret;
+    if (neg) {
+        if (v - 1 > LLONG_MAX) {
+            errno = ERANGE;
+            return -1;
+        }
+        *output = -(long long) v;
+        return 0;
+    } else {
+        if (v > LLONG_MAX) {
+            errno = ERANGE;
+            return -1;
+        }
+        *output = (long long) v;
+        return 0;
+    }
+}
+
+int cx_strtoi8_lc(cxstring str, int8_t *output, int base, const char *groupsep) {
+    cx_strtoX_signed_impl(int8_t, INT8_MIN, INT8_MAX);
+}
+
+int cx_strtoi16_lc(cxstring str, int16_t *output, int base, const char *groupsep) {
+    cx_strtoX_signed_impl(int16_t, INT16_MIN, INT16_MAX);
+}
+
+int cx_strtoi32_lc(cxstring str, int32_t *output, int base, const char *groupsep) {
+    cx_strtoX_signed_impl(int32_t, INT32_MIN, INT32_MAX);
+}
+
+int cx_strtoi64_lc(cxstring str, int64_t *output, int base, const char *groupsep) {
+    assert(sizeof(long long) == sizeof(int64_t)); // should be true on all platforms
+    return cx_strtoll_lc(str, (long long*) output, base, groupsep);
+}
+
+int cx_strtoz_lc(cxstring str, ssize_t *output, int base, const char *groupsep) {
+#if SSIZE_MAX == INT32_MAX
+    return cx_strtoi32_lc(str, (int32_t*) output, base, groupsep);
+#elif SSIZE_MAX == INT64_MAX
+    return cx_strtoll_lc(str, (long long*) output, base, groupsep);
+#else
+#error "unsupported ssize_t size"
+#endif
+}
+
+#define cx_strtoX_unsigned_impl(rtype, rmax) \
+    uint64_t result; \
+    if (cx_strtou64_lc(str, &result, base, groupsep)) { \
+        return -1; \
+    } \
+    if (result > rmax) { \
+        errno = ERANGE; \
+        return -1; \
+    } \
+    *output = (rtype) result; \
+    return 0
+
+int cx_strtous_lc(cxstring str, unsigned short *output, int base, const char *groupsep) {
+    cx_strtoX_unsigned_impl(unsigned short, USHRT_MAX);
+}
+
+int cx_strtou_lc(cxstring str, unsigned int *output, int base, const char *groupsep) {
+    cx_strtoX_unsigned_impl(unsigned int, UINT_MAX);
+}
+
+int cx_strtoul_lc(cxstring str, unsigned long *output, int base, const char *groupsep) {
+    cx_strtoX_unsigned_impl(unsigned long, ULONG_MAX);
+}
+
+int cx_strtoull_lc(cxstring str, unsigned long long *output, int base, const char *groupsep) {
+    // some sanity checks
+    str = cx_strtrim(str);
+    if (str.length == 0) {
+        errno = EINVAL;
+        return -1;
+    }
+    if (!(base == 2 || base == 8 || base == 10 || base == 16)) {
+        errno = EINVAL;
+        return -1;
+    }
+    if (groupsep == NULL) groupsep = "";
+
+    // find the actual start of the number
+    if (str.ptr[0] == '+') {
+        str.ptr++;
+        str.length--;
+        if (str.length == 0) {
+            errno = EINVAL;
+            return -1;
+        }
+    }
+    size_t start = 0;
+
+    // if base is 2 or 16, some leading stuff may appear
+    if (base == 2) {
+        if ((str.ptr[0] | 32) == 'b') {
+            start = 1;
+        } else if (str.ptr[0] == '0' && str.length > 1) {
+            if ((str.ptr[1] | 32) == 'b') {
+                start = 2;
+            }
+        }
+    } else if (base == 16) {
+        if ((str.ptr[0] | 32) == 'x' || str.ptr[0] == '#') {
+            start = 1;
+        } else if (str.ptr[0] == '0' && str.length > 1) {
+            if ((str.ptr[1] | 32) == 'x') {
+                start = 2;
+            }
+        }
+    }
+
+    // check if there are digits left
+    if (start >= str.length) {
+        errno = EINVAL;
+        return -1;
+    }
+
+    // now parse the number
+    unsigned long long result = 0;
+    for (size_t i = start; i < str.length; i++) {
+        // ignore group separators
+        if (strchr(groupsep, str.ptr[i])) continue;
+
+        // determine the digit value of the character
+        unsigned char c = str.ptr[i];
+        if (c >= 'a') c = 10 + (c - 'a');
+        else if (c >= 'A') c = 10 + (c - 'A');
+        else if (c >= '0') c = c - '0';
+        else c = 255;
+        if (c >= base) {
+            errno = EINVAL;
+            return -1;
+        }
+
+        // now combine the digit with what we already have
+        unsigned long right = (result & 0xff) * base + c;
+        unsigned long long left = (result >> 8) * base + (right >> 8);
+        if (left > (ULLONG_MAX >> 8)) {
+            errno = ERANGE;
+            return -1;
+        }
+        result = (left << 8) + (right & 0xff);
+    }
+
+    *output = result;
+    return 0;
+}
+
+int cx_strtou8_lc(cxstring str, uint8_t *output, int base, const char *groupsep) {
+    cx_strtoX_unsigned_impl(uint8_t, UINT8_MAX);
+}
+
+int cx_strtou16_lc(cxstring str, uint16_t *output, int base, const char *groupsep) {
+    cx_strtoX_unsigned_impl(uint16_t, UINT16_MAX);
+}
+
+int cx_strtou32_lc(cxstring str, uint32_t *output, int base, const char *groupsep) {
+    cx_strtoX_unsigned_impl(uint32_t, UINT32_MAX);
+}
+
+int cx_strtou64_lc(cxstring str, uint64_t *output, int base, const char *groupsep) {
+    assert(sizeof(unsigned long long) == sizeof(uint64_t)); // should be true on all platforms
+    return cx_strtoull_lc(str, (unsigned long long*) output, base, groupsep);
+}
+
+int cx_strtouz_lc(cxstring str, size_t *output, int base, const char *groupsep) {
+#if SIZE_MAX == UINT32_MAX
+    return cx_strtou32_lc(str, (uint32_t*) output, base, groupsep);
+#elif SIZE_MAX == UINT64_MAX
+    return cx_strtoull_lc(str, (unsigned long long *) output, base, groupsep);
+#else
+#error "unsupported size_t size"
+#endif
+}
+
+int cx_strtof_lc(cxstring str, float *output, char decsep, const char *groupsep) {
+    // use string to double and add a range check
+    double d;
+    int ret = cx_strtod_lc(str, &d, decsep, groupsep);
+    if (ret != 0) return ret;
+    // note: FLT_MIN is the smallest POSITIVE number that can be represented
+    double test = d < 0 ? -d : d;
+    if (test < FLT_MIN || test > FLT_MAX) {
+        errno = ERANGE;
+        return -1;
+    }
+    *output = (float) d;
+    return 0;
+}
+
+int cx_strtod_lc(cxstring str, double *output, char decsep, const char *groupsep) {
+    // TODO: overflow check
+    // TODO: increase precision
+
+    // trim and check
+    str = cx_strtrim(str);
+    if (str.length == 0) {
+        errno = EINVAL;
+        return -1;
+    }
+
+    double result = 0.;
+    int sign = 1;
+
+    // check if there is a sign
+    if (str.ptr[0] == '-') {
+        sign = -1;
+        str.ptr++;
+        str.length--;
+    } else if (str.ptr[0] == '+') {
+        str.ptr++;
+        str.length--;
+    }
+
+    // there must be at least one char to parse
+    if (str.length == 0) {
+        errno = EINVAL;
+        return -1;
+    }
+
+    // parse all digits until we find the decsep
+    size_t pos = 0;
+    do {
+        if (isdigit(str.ptr[pos])) {
+            result = result * 10 + (str.ptr[pos] - '0');
+        } else if (strchr(groupsep, str.ptr[pos]) == NULL) {
+            break;
+        }
+    } while (++pos < str.length);
+
+    // already done?
+    if (pos == str.length) {
+        *output = result * sign;
+        return 0;
+    }
+
+    // is the next char the decsep?
+    if (str.ptr[pos] == decsep) {
+        pos++;
+        // it may end with the decsep, if it did not start with it
+        if (pos == str.length) {
+            if (str.length == 1) {
+                errno = EINVAL;
+                return -1;
+            } else {
+                *output = result * sign;
+                return 0;
+            }
+        }
+        // parse everything until exponent or end
+        double factor = 1.;
+        do {
+            if (isdigit(str.ptr[pos])) {
+                factor *= 0.1;
+                result = result + factor * (str.ptr[pos] - '0');
+            } else if (strchr(groupsep, str.ptr[pos]) == NULL) {
+                break;
+            }
+        } while (++pos < str.length);
+    }
+
+    // no exponent?
+    if (pos == str.length) {
+        *output = result * sign;
+        return 0;
+    }
+
+    // now the next separator MUST be the exponent separator
+    // and at least one char must follow
+    if ((str.ptr[pos] | 32) != 'e' || str.length <= pos + 1) {
+        errno = EINVAL;
+        return -1;
+    }
+    pos++;
+
+    // check if we have a sign for the exponent
+    double factor = 10.;
+    if (str.ptr[pos] == '-') {
+        factor = .1;
+        pos++;
+    } else if (str.ptr[pos] == '+') {
+        pos++;
+    }
+
+    // at least one digit must follow
+    if (pos == str.length) {
+        errno = EINVAL;
+        return -1;
+    }
+
+    // parse the exponent
+    unsigned int exp = 0;
+    do {
+        if (isdigit(str.ptr[pos])) {
+            exp = 10 * exp + (str.ptr[pos] - '0');
+        } else if (strchr(groupsep, str.ptr[pos]) == NULL) {
+            errno = EINVAL;
+            return -1;
+        }
+    } while (++pos < str.length);
+
+    // apply the exponent by fast exponentiation
+    do {
+        if (exp & 1) {
+            result *= factor;
+        }
+        factor *= factor;
+    } while ((exp >>= 1) > 0);
+
+    // store the result and exit
+    *output = result * sign;
+    return 0;
+}

mercurial