# HG changeset patch # User Mike Becker # Date 1661882167 -7200 # Node ID bbc46dcd5255f3f8aa1cd0a05056708a43231529 # Parent 0b2c0cb280a95b3410574f943227624fb093b470 start implementing string functions diff -r 0b2c0cb280a9 -r bbc46dcd5255 src/string.c --- 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 +#include +#include + +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; +} + + +