-
- ssize_t nmax = *n;
- size_t arrlen = 16;
- sstr_t* result = (sstr_t*) alcalloc(allocator, arrlen, sizeof(sstr_t));
-
- if (result) {
- scstr_t curpos = s;
- ssize_t j = 1;
- while (1) {
- scstr_t match;
- /* optimize for one byte delimiters */
- if (d.length == 1) {
- match = curpos;
- for (size_t i = 0 ; i < curpos.length ; i++) {
- if (curpos.ptr[i] == *(d.ptr)) {
- match.ptr = curpos.ptr + i;
- break;
- }
- match.length--;
- }
- } else {
- match = scstrscstr(curpos, d);
- }
- if (match.length > 0) {
- /* is this our last try? */
- if (nmax == 0 || j < nmax) {
- /* copy the current string to the array */
- scstr_t item = scstrn(curpos.ptr, match.ptr - curpos.ptr);
- result[j-1] = sstrdup_a(allocator, item);
- size_t processed = item.length + d.length;
- curpos.ptr += processed;
- curpos.length -= processed;
-
- /* allocate memory for the next string */
- j++;
- if (j > arrlen) {
- arrlen *= 2;
- size_t reallocsz;
- sstr_t* reallocated = NULL;
- if(!ucx_szmul(arrlen, sizeof(sstr_t), &reallocsz)) {
- reallocated = (sstr_t*) alrealloc(
- allocator, result, reallocsz);
- }
- if (reallocated) {
- result = reallocated;
- } else {
- for (ssize_t i = 0 ; i < j-1 ; i++) {
- alfree(allocator, result[i].ptr);
- }
- alfree(allocator, result);
- *n = -2;
- return NULL;
- }
- }
- } else {
- /* nmax reached, copy the _full_ remaining string */
- result[j-1] = sstrdup_a(allocator, curpos);
- break;
- }
+
+ return n;
+}
+
+size_t cx_strsplit_a(
+ CxAllocator *allocator,
+ cxstring string,
+ cxstring delim,
+ size_t limit,
+ cxstring **output
+) {
+ // find out how many splits we're going to make and allocate memory
+ size_t n = 0;
+ cxstring curpos = string;
+ while (1) {
+ ++n;
+ cxstring match = cx_strstr(curpos, delim);
+ if (match.length > 0) {
+ // is the limit reached?
+ if (n < limit) {
+ size_t processed = match.ptr - curpos.ptr + delim.length;
+ curpos.ptr += processed;
+ curpos.length -= processed;