2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
4 * Copyright 2021 Mike Becker, Olaf Wintermann All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 * POSSIBILITY OF SUCH DAMAGE.
29 #include "cx/string.h"
38 #include <strings.h> // for strncasecmp()
42 cxmutstr cx_mutstr(char *cstring) {
43 return (cxmutstr) {cstring, strlen(cstring)};
50 return (cxmutstr) {cstring, length};
53 cxstring cx_str(const char *cstring) {
54 return (cxstring) {cstring, strlen(cstring)};
61 return (cxstring) {cstring, length};
64 cxstring cx_strcast(cxmutstr str) {
65 return (cxstring) {str.ptr, str.length};
68 void cx_strfree(cxmutstr *str) {
75 CxAllocator const *alloc,
78 cxFree(alloc, str->ptr);
87 if (count == 0) return 0;
93 cxstring str = va_arg(ap, cxstring);
101 cxmutstr cx_strcat_ma(
102 CxAllocator const *alloc,
107 if (count == 0) return str;
109 cxstring *strings = calloc(count, sizeof(cxstring));
110 if (!strings) abort();
115 // get all args and overall length
116 size_t slen = str.length;
118 cxstring s = va_arg (ap, cxstring);
124 // reallocate or create new string
125 if (str.ptr == NULL) {
126 str.ptr = cxMalloc(alloc, slen + 1);
128 str.ptr = cxRealloc(alloc, str.ptr, slen + 1);
130 if (str.ptr == NULL) abort();
132 // concatenate strings
133 size_t pos = str.length;
136 cxstring s = strings[i];
137 memcpy(str.ptr + pos, s.ptr, s.length);
142 str.ptr[str.length] = '\0';
144 // free temporary array
154 return cx_strsubsl(string, start, string.length - start);
157 cxmutstr cx_strsubs_m(
161 return cx_strsubsl_m(string, start, string.length - start);
164 cxstring cx_strsubsl(
169 if (start > string.length) {
170 return (cxstring) {NULL, 0};
173 size_t rem_len = string.length - start;
174 if (length > rem_len) {
178 return (cxstring) {string.ptr + start, length};
181 cxmutstr cx_strsubsl_m(
186 cxstring result = cx_strsubsl(cx_strcast(string), start, length);
187 return (cxmutstr) {(char *) result.ptr, result.length};
195 // TODO: improve by comparing multiple bytes at once
196 cx_for_n(i, string.length) {
197 if (string.ptr[i] == chr) {
198 return cx_strsubs(string, i);
201 return (cxstring) {NULL, 0};
204 cxmutstr cx_strchr_m(
208 cxstring result = cx_strchr(cx_strcast(string), chr);
209 return (cxmutstr) {(char *) result.ptr, result.length};
217 size_t i = string.length;
220 // TODO: improve by comparing multiple bytes at once
221 if (string.ptr[i] == chr) {
222 return cx_strsubs(string, i);
225 return (cxstring) {NULL, 0};
228 cxmutstr cx_strrchr_m(
232 cxstring result = cx_strrchr(cx_strcast(string), chr);
233 return (cxmutstr) {(char *) result.ptr, result.length};
236 #ifndef CX_STRSTR_SBO_SIZE
237 #define CX_STRSTR_SBO_SIZE 512
244 if (needle.length == 0) {
248 // optimize for single-char needles
249 if (needle.length == 1) {
250 return cx_strchr(haystack, *needle.ptr);
255 * Our prefix table contains the prefix length PLUS ONE
256 * this is our decision, because we want to use the full range of size_t.
257 * The original algorithm needs a (-1) at one single place,
258 * and we want to avoid that.
261 // local prefix table
262 size_t s_prefix_table[CX_STRSTR_SBO_SIZE];
264 // check needle length and use appropriate prefix table
265 // if the pattern exceeds static prefix table, allocate on the heap
266 bool useheap = needle.length >= CX_STRSTR_SBO_SIZE;
267 register size_t *ptable = useheap ? calloc(needle.length + 1,
268 sizeof(size_t)) : s_prefix_table;
270 // keep counter in registers
271 register size_t i, j;
277 while (i < needle.length) {
278 while (j >= 1 && needle.ptr[j - 1] != needle.ptr[i]) {
287 cxstring result = {NULL, 0};
290 while (i < haystack.length) {
291 while (j >= 1 && haystack.ptr[i] != needle.ptr[j - 1]) {
296 if (j - 1 == needle.length) {
297 size_t start = i - needle.length;
298 result.ptr = haystack.ptr + start;
299 result.length = haystack.length - start;
304 // if prefix table was allocated on the heap, free it
305 if (ptable != s_prefix_table) {
312 cxmutstr cx_strstr_m(
316 cxstring result = cx_strstr(cx_strcast(haystack), needle);
317 return (cxmutstr) {(char *) result.ptr, result.length};
326 // special case: output limit is zero
327 if (limit == 0) return 0;
329 // special case: delimiter is empty
330 if (delim.length == 0) {
335 // special cases: delimiter is at least as large as the string
336 if (delim.length >= string.length) {
338 if (cx_strcmp(string, delim) == 0) {
339 output[0] = cx_strn(string.ptr, 0);
340 output[1] = cx_strn(string.ptr + string.length, 0);
350 cxstring curpos = string;
353 cxstring match = cx_strstr(curpos, delim);
354 if (match.length > 0) {
355 // is the limit reached?
357 // copy the current string to the array
358 cxstring item = cx_strn(curpos.ptr, match.ptr - curpos.ptr);
359 output[n - 1] = item;
360 size_t processed = item.length + delim.length;
361 curpos.ptr += processed;
362 curpos.length -= processed;
364 // limit reached, copy the _full_ remaining string
365 output[n - 1] = curpos;
369 // no more matches, copy last string
370 output[n - 1] = curpos;
378 size_t cx_strsplit_a(
379 CxAllocator const *allocator,
385 // find out how many splits we're going to make and allocate memory
387 cxstring curpos = string;
390 cxstring match = cx_strstr(curpos, delim);
391 if (match.length > 0) {
392 // is the limit reached?
394 size_t processed = match.ptr - curpos.ptr + delim.length;
395 curpos.ptr += processed;
396 curpos.length -= processed;
406 *output = cxCalloc(allocator, n, sizeof(cxstring));
407 return cx_strsplit(string, delim, n, *output);
410 size_t cx_strsplit_m(
416 return cx_strsplit(cx_strcast(string),
417 delim, limit, (cxstring *) output);
420 size_t cx_strsplit_ma(
421 CxAllocator const *allocator,
427 return cx_strsplit_a(allocator, cx_strcast(string),
428 delim, limit, (cxstring **) output);
435 if (s1.length == s2.length) {
436 return memcmp(s1.ptr, s2.ptr, s1.length);
437 } else if (s1.length > s2.length) {
448 if (s1.length == s2.length) {
450 return _strnicmp(s1.ptr, s2.ptr, s1.length);
452 return strncasecmp(s1.ptr, s2.ptr, s1.length);
454 } else if (s1.length > s2.length) {
465 cxstring const *left = s1;
466 cxstring const *right = s2;
467 return cx_strcmp(*left, *right);
474 cxstring const *left = s1;
475 cxstring const *right = s2;
476 return cx_strcasecmp(*left, *right);
479 cxmutstr cx_strdup_a(
480 CxAllocator const *allocator,
484 cxMalloc(allocator, string.length + 1),
487 if (result.ptr == NULL) {
491 memcpy(result.ptr, string.ptr, string.length);
492 result.ptr[string.length] = '\0';
496 cxstring cx_strtrim(cxstring string) {
497 cxstring result = string;
498 // TODO: optimize by comparing multiple bytes at once
499 while (result.length > 0 && isspace(*result.ptr)) {
503 while (result.length > 0 && isspace(result.ptr[result.length - 1])) {
509 cxmutstr cx_strtrim_m(cxmutstr string) {
510 cxstring result = cx_strtrim(cx_strcast(string));
511 return (cxmutstr) {(char *) result.ptr, result.length};
518 if (string.length < prefix.length) return false;
519 return memcmp(string.ptr, prefix.ptr, prefix.length) == 0;
526 if (string.length < suffix.length) return false;
527 return memcmp(string.ptr + string.length - suffix.length,
528 suffix.ptr, suffix.length) == 0;
531 bool cx_strcaseprefix(
535 if (string.length < prefix.length) return false;
537 return _strnicmp(string.ptr, prefix.ptr, prefix.length) == 0;
539 return strncasecmp(string.ptr, prefix.ptr, prefix.length) == 0;
543 bool cx_strcasesuffix(
547 if (string.length < suffix.length) return false;
549 return _strnicmp(string.ptr+string.length-suffix.length,
550 suffix.ptr, suffix.length) == 0;
552 return strncasecmp(string.ptr + string.length - suffix.length,
553 suffix.ptr, suffix.length) == 0;
557 void cx_strlower(cxmutstr string) {
558 cx_for_n(i, string.length) {
559 string.ptr[i] = (char) tolower(string.ptr[i]);
563 void cx_strupper(cxmutstr string) {
564 cx_for_n(i, string.length) {
565 string.ptr[i] = (char) toupper(string.ptr[i]);
569 #ifndef CX_STRREPLACE_INDEX_BUFFER_SIZE
570 #define CX_STRREPLACE_INDEX_BUFFER_SIZE 64
573 struct cx_strreplace_ibuf {
575 struct cx_strreplace_ibuf *next;
579 static void cx_strrepl_free_ibuf(struct cx_strreplace_ibuf *buf) {
581 struct cx_strreplace_ibuf *next = buf->next;
588 cxmutstr cx_strreplacen_a(
589 CxAllocator const *allocator,
592 cxstring replacement,
596 if (pattern.length == 0 || pattern.length > str.length || replmax == 0)
597 return cx_strdup_a(allocator, str);
599 // Compute expected buffer length
600 size_t ibufmax = str.length / pattern.length;
601 size_t ibuflen = replmax < ibufmax ? replmax : ibufmax;
602 if (ibuflen > CX_STRREPLACE_INDEX_BUFFER_SIZE) {
603 ibuflen = CX_STRREPLACE_INDEX_BUFFER_SIZE;
606 // Allocate first index buffer
607 struct cx_strreplace_ibuf *firstbuf, *curbuf;
608 firstbuf = curbuf = calloc(1, sizeof(struct cx_strreplace_ibuf));
609 if (!firstbuf) return cx_mutstrn(NULL, 0);
610 firstbuf->buf = calloc(ibuflen, sizeof(size_t));
611 if (!firstbuf->buf) {
613 return cx_mutstrn(NULL, 0);
616 // Search occurrences
617 cxstring searchstr = str;
620 cxstring match = cx_strstr(searchstr, pattern);
621 if (match.length > 0) {
622 // Allocate next buffer in chain, if required
623 if (curbuf->len == ibuflen) {
624 struct cx_strreplace_ibuf *nextbuf =
625 calloc(1, sizeof(struct cx_strreplace_ibuf));
627 cx_strrepl_free_ibuf(firstbuf);
628 return cx_mutstrn(NULL, 0);
630 nextbuf->buf = calloc(ibuflen, sizeof(size_t));
633 cx_strrepl_free_ibuf(firstbuf);
634 return cx_mutstrn(NULL, 0);
636 curbuf->next = nextbuf;
640 // Record match index
642 size_t idx = match.ptr - str.ptr;
643 curbuf->buf[curbuf->len++] = idx;
644 searchstr.ptr = match.ptr + pattern.length;
645 searchstr.length = str.length - idx - pattern.length;
649 } while (searchstr.length > 0 && found < replmax);
651 // Allocate result string
654 ssize_t adjlen = (ssize_t) replacement.length - (ssize_t) pattern.length;
658 rcount += curbuf->len;
659 curbuf = curbuf->next;
661 result.length = str.length + rcount * adjlen;
662 result.ptr = cxMalloc(allocator, result.length + 1);
664 cx_strrepl_free_ibuf(firstbuf);
665 return cx_mutstrn(NULL, 0);
669 // Build result string
672 char *destptr = result.ptr;
674 for (size_t i = 0; i < curbuf->len; i++) {
675 // Copy source part up to next match
676 size_t idx = curbuf->buf[i];
677 size_t srclen = idx - srcidx;
679 memcpy(destptr, str.ptr + srcidx, srclen);
684 // Copy the replacement and skip the source pattern
685 srcidx += pattern.length;
686 memcpy(destptr, replacement.ptr, replacement.length);
687 destptr += replacement.length;
689 curbuf = curbuf->next;
691 memcpy(destptr, str.ptr + srcidx, str.length - srcidx);
693 // Result is guaranteed to be zero-terminated
694 result.ptr[result.length] = '\0';
697 cx_strrepl_free_ibuf(firstbuf);
702 CxStrtokCtx cx_strtok(
715 ctx.delim_more = NULL;
716 ctx.delim_more_count = 0;
720 CxStrtokCtx cx_strtok_m(
725 return cx_strtok(cx_strcast(str), delim, limit);
733 if (ctx->found >= ctx->limit || ctx->delim_pos >= ctx->str.length) {
737 // determine the search start
738 cxstring haystack = cx_strsubs(ctx->str, ctx->next_pos);
740 // search the next delimiter
741 cxstring delim = cx_strstr(haystack, ctx->delim);
743 // if found, make delim capture exactly the delimiter
744 if (delim.length > 0) {
745 delim.length = ctx->delim.length;
748 // if more delimiters are specified, check them now
749 if (ctx->delim_more_count > 0) {
750 cx_for_n(i, ctx->delim_more_count) {
751 cxstring d = cx_strstr(haystack, ctx->delim_more[i]);
752 if (d.length > 0 && (delim.length == 0 || d.ptr < delim.ptr)) {
754 delim.length = ctx->delim_more[i].length;
759 // store the token information and adjust the context
761 ctx->pos = ctx->next_pos;
762 token->ptr = &ctx->str.ptr[ctx->pos];
763 ctx->delim_pos = delim.length == 0 ?
764 ctx->str.length : (size_t) (delim.ptr - ctx->str.ptr);
765 token->length = ctx->delim_pos - ctx->pos;
766 ctx->next_pos = ctx->delim_pos + delim.length;
771 bool cx_strtok_next_m(
775 return cx_strtok_next(ctx, (cxstring *) token);
778 void cx_strtok_delim(
780 cxstring const *delim,
783 ctx->delim_more = delim;
784 ctx->delim_more_count = count;