Line data Source code
1 : /*
2 : MIT License
3 :
4 : Copyright (c) 2026 - A bunch of nerds
5 :
6 : Permission is hereby granted, free of charge, to any person obtaining a copy
7 : of this software and associated documentation files (the "Software"), to deal
8 : in the Software without restriction, including without limitation the rights
9 : to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 : copies of the Software, and to permit persons to whom the Software is
11 : furnished to do so, subject to the following conditions:
12 :
13 : The above copyright notice and this permission notice shall be included in all
14 : copies or substantial portions of the Software.
15 :
16 : THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 : IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 : FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 : AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 : LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 : OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 : SOFTWARE.
23 : */
24 :
25 : // cstring_rfind() uses memrchr(), which is a GNU extension.
26 : #ifndef _GNU_SOURCE
27 : #define _GNU_SOURCE
28 : #endif
29 :
30 : #include <cstring.h>
31 : #include <internal/cascii.h>
32 : #include <internal/cpow2.h>
33 : #include <internal/cprocsintern.h>
34 : #include <internal/test_helpers/cstring.h>
35 :
36 : // Finds the last byte c in the n bytes at s, or gives NULL. cstring_rfind()
37 : // needs memrchr(), which glibc and FreeBSD have and macOS doesn't, so there
38 : // this backward scan takes its place. CCOL_EMULATE_DARWIN_MEMRCHR selects it on
39 : // other systems too, for the test suites.
40 : #if defined(__APPLE__) || defined(CCOL_EMULATE_DARWIN_MEMRCHR)
41 : static const void *cstring_memrchr(const void *s, int c, size_t n) {
42 : const unsigned char *p = (const unsigned char *)s + n;
43 : const unsigned char b = (unsigned char)c;
44 : while (p != (const unsigned char *)s) {
45 : if (*--p == b) return p;
46 : }
47 : return NULL;
48 : }
49 : #else
50 : // Elsewhere cstring_memrchr is the C library's memrchr().
51 : #define cstring_memrchr memrchr
52 : #endif
53 :
54 : // The smallest buffer a string ever has; creation and reset start from it.
55 : static const size_t cstring_minimum_capacity = 16;
56 :
57 : // The string. data holds length bytes and a '\0' in capacity bytes. m_procs is
58 : // NULL for the default allocator, an interned procs pointer, or a pointer to
59 : // the copy right after this struct in the same block.
60 : struct cstring {
61 : char *data;
62 : size_t length;
63 : size_t capacity;
64 : ccol_memmgmt_procs *m_procs;
65 : };
66 :
67 : // The procs copy after the struct must be aligned for its type.
68 : _Static_assert(sizeof(struct cstring) % _Alignof(ccol_memmgmt_procs) == 0,
69 : "the procs copy after struct cstring must be aligned");
70 :
71 : // Frees the buffer and the string's block; cstring_destroy() and the scoped
72 : // cleanup call it. NULL is fine. The free function is read before the block
73 : // goes away, because m_procs can point into that block.
74 20659 : void cstring__destroy(cstr s) {
75 20659 : if (s) {
76 20659 : ccol__mem_free(s->m_procs, s->data);
77 :
78 20659 : if (s->m_procs) {
79 48 : ccol_free free_func = s->m_procs->free;
80 48 : free_func(s);
81 : } else {
82 20611 : ccol__default_mem_free(s);
83 : }
84 : }
85 20659 : }
86 :
87 : // Says whether length + 1 fits in a size_t. Every function that sizes a buffer
88 : // as length + 1 checks this first: A length of SIZE_MAX would wrap to a
89 : // capacity of 0, which cstring_grow_to() takes as already enough, and the copy
90 : // would then run past the real buffer.
91 4 : static bool cstring_length_fits_with_terminator(size_t length) {
92 4 : return length != ccol_invalid_size;
93 : }
94 :
95 : // Grows the buffer of s to at least needed_capacity bytes, rounded up to a
96 : // power of two (16 at least), so a run of appends reallocates rarely. Every
97 : // function that makes the string longer calls it. Gives false, with s
98 : // unchanged, when the size can't be represented or the realloc fails. Updates
99 : // s->data and s->capacity.
100 189 : static bool cstring_grow_to(cstr s, size_t needed_capacity) {
101 189 : if (needed_capacity <= s->capacity) {
102 : return true;
103 : }
104 :
105 39 : size_t new_cap = ccol__find_nearest_gte_power_of_two(needed_capacity);
106 39 : if (new_cap == ccol_invalid_size) {
107 : return false;
108 : }
109 38 : if (new_cap < cstring_minimum_capacity) {
110 : new_cap = cstring_minimum_capacity;
111 : }
112 :
113 38 : char *orig = s->data;
114 38 : s->data = (char *)ccol__mem_realloc(s->m_procs, s->data, new_cap);
115 38 : if (!s->data) {
116 5 : s->data = orig;
117 5 : return false;
118 : }
119 :
120 33 : s->capacity = new_cap;
121 33 : return true;
122 : }
123 :
124 : // Destroys every cstr in v and then v, so a split that fails halfway can undo
125 : // what it built and give NULL instead of a partial result.
126 3 : static void destroy_cstr_vector(cvec v) {
127 3 : if (!v) {
128 : return;
129 : }
130 3 : size_t count = cvector_size(v);
131 7 : for (size_t i = 0; i < count; i++) {
132 4 : cstr *part = (cstr *)cvector_at(v, i);
133 4 : if (part && *part) {
134 4 : cstring__destroy(*part);
135 : }
136 : }
137 3 : cvector__destroy(v);
138 : }
139 :
140 : // Creates a string holding the init_len bytes at initial (NULL is fine when
141 : // init_len is 0; the bytes hold no '\0'). Creation, substring and split all
142 : // build strings here, so the checks and the allocation logic live in one place.
143 : // The buffer gets its final size at once: The power of two above init_len + 1,
144 : // 16 at least. An interned procs pointer is kept as it is; any other procs
145 : // struct is copied into the tail of the string's block, so a string costs two
146 : // allocations and never points at the caller's struct. Gives NULL with *err set
147 : // on failure, after freeing what it allocated.
148 20671 : static cstr cstring_create_from_span(const char *initial, size_t init_len,
149 : ccol_memmgmt_procs *m_procs, char **err) {
150 20671 : if (!ccol__verify_memmgmt_procs(m_procs, err)) {
151 4 : return NULL;
152 : }
153 :
154 20667 : bool copy_procs = m_procs && !ccol_procs_is_interned(m_procs);
155 20668 : cstr s = (cstr)ccol__mem_calloc(
156 : m_procs, 1,
157 : sizeof(cstring) + (copy_procs ? sizeof(ccol_memmgmt_procs) : 0));
158 20667 : if (!s) {
159 6 : if (err) {
160 6 : *err = CCOL__ERR_STR("failed to allocate cstring container");
161 : }
162 6 : return NULL;
163 : }
164 :
165 20661 : if (copy_procs) {
166 48 : s->m_procs = (ccol_memmgmt_procs *)(s + 1);
167 48 : memcpy(s->m_procs, m_procs, sizeof(ccol_memmgmt_procs));
168 : } else {
169 20613 : s->m_procs = m_procs;
170 : }
171 :
172 20661 : if (!cstring_length_fits_with_terminator(init_len)) {
173 0 : cstring__destroy(s);
174 0 : if (err) {
175 0 : *err = CCOL__ERR_STR("initial string too large");
176 : }
177 0 : return NULL;
178 : }
179 20661 : size_t init_cap = ccol__find_nearest_gte_power_of_two(init_len + 1);
180 20661 : if (init_cap == ccol_invalid_size) {
181 0 : cstring__destroy(s);
182 0 : if (err) {
183 0 : *err = CCOL__ERR_STR("initial string too large");
184 : }
185 0 : return NULL;
186 : }
187 20661 : if (init_cap < cstring_minimum_capacity) {
188 : init_cap = cstring_minimum_capacity;
189 : }
190 :
191 20661 : s->data = (char *)ccol__mem_alloc(s->m_procs, init_cap);
192 20661 : if (!s->data) {
193 3 : cstring__destroy(s);
194 3 : if (err) {
195 3 : *err = CCOL__ERR_STR("failed to allocate cstring data buffer");
196 : }
197 3 : return NULL;
198 : }
199 :
200 20658 : if (init_len > 0) {
201 20458 : memcpy(s->data, initial, init_len);
202 : }
203 20658 : s->data[init_len] = '\0';
204 20658 : s->length = init_len;
205 20658 : s->capacity = init_cap;
206 :
207 20658 : if (err) {
208 66 : *err = NULL;
209 : }
210 : return s;
211 : }
212 :
213 : // Creates a string holding a copy of the C string initial (NULL for empty),
214 : // allocating through m_procs. It's the public constructor behind every create
215 : // function and cstr_construct form. Gives NULL with *err set on failure.
216 20624 : cstr cstring_create_full(const char *initial, ccol_memmgmt_procs *m_procs,
217 : char **err) {
218 20624 : return cstring_create_from_span(initial, initial ? strlen(initial) : 0,
219 : m_procs, err);
220 : }
221 :
222 : // Gives the allocator of s (NULL for the default), so a caller can allocate
223 : // related memory the same way. Asserts on a NULL s.
224 5 : ccol_memmgmt_procs *cstring_get_mprocs(cstr s) {
225 5 : if (!s) {
226 1 : ccol__assert(false);
227 : }
228 4 : return s->m_procs;
229 : }
230 :
231 : // Gives the length of s without the '\0', kept up to date by every operation.
232 : // Asserts on a NULL s.
233 61 : size_t cstring_length(cstr s) {
234 61 : if (!s) {
235 1 : ccol__assert(false);
236 : }
237 60 : return s->length;
238 : }
239 :
240 : // Gives the NUL-terminated buffer of s, for APIs that take a char *. Any change
241 : // to s can make it invalid. Asserts on a NULL s.
242 168 : const char *cstring_c_str(cstr s) {
243 168 : if (!s) {
244 1 : ccol__assert(false);
245 : }
246 167 : return s->data;
247 : }
248 :
249 : // Gives the byte at idx, or '\0' out of range, so a bad index isn't fatal.
250 : // Asserts on a NULL s.
251 12 : char cstring_at(cstr s, size_t idx) {
252 12 : if (!s) {
253 1 : ccol__assert(false);
254 : }
255 11 : if (idx >= s->length) {
256 : return '\0';
257 : }
258 8 : return s->data[idx];
259 : }
260 :
261 : // Says whether s holds no bytes. Asserts on a NULL s.
262 8 : bool cstring_is_empty(cstr s) {
263 8 : if (!s) {
264 1 : ccol__assert(false);
265 : }
266 7 : return s->length == 0;
267 : }
268 :
269 : // Appends str to s, growing the buffer when needed; the most common way to
270 : // build a string. Gives ccol_success (also for an empty str), ccol_invalid_args
271 : // for a NULL str, ccol_container_full on a length overflow or
272 : // ccol_not_enough_memory. str may point into s; its offset is saved before the
273 : // buffer can move. The function is 64-byte aligned on purpose: The short block
274 : // that a non-growing append jumps to must sit in one 64-byte line, and at an
275 : // offset of 32 or 48 bytes every append costs about 45 percent more. After a
276 : // change here or a compiler change, check the block with objdump.
277 146 : __attribute__((aligned(64))) ccol_retval cstring_append(cstr s,
278 : const char *str) {
279 146 : if (!s) {
280 1 : ccol__assert(false);
281 : }
282 145 : if (!str) {
283 : return ccol_invalid_args;
284 : }
285 :
286 144 : size_t str_len = strlen(str);
287 144 : if (str_len == 0) {
288 : return ccol_success;
289 : }
290 :
291 143 : size_t new_len = s->length + str_len;
292 143 : if (new_len < s->length || !cstring_length_fits_with_terminator(new_len)) {
293 : return ccol_container_full;
294 : }
295 :
296 286 : ptrdiff_t alias_off =
297 143 : (str >= s->data && str < s->data + s->capacity) ? (str - s->data) : -1;
298 :
299 143 : if (!cstring_grow_to(s, new_len + 1)) {
300 : return ccol_not_enough_memory;
301 : }
302 :
303 142 : if (alias_off >= 0) {
304 3 : str = s->data + alias_off;
305 : }
306 :
307 142 : memcpy(s->data + s->length, str, str_len);
308 142 : s->length = new_len;
309 142 : s->data[s->length] = '\0';
310 :
311 142 : return ccol_success;
312 : }
313 :
314 : // Puts str in front of the content of s. The buffer grows first, then the old
315 : // content moves right with memmove. str may point into s; its offset is saved
316 : // before the buffer can move and moved again by the shift. Results as for
317 : // cstring_append().
318 12 : ccol_retval cstring_prepend(cstr s, const char *str) {
319 12 : if (!s) {
320 1 : ccol__assert(false);
321 : }
322 11 : if (!str) {
323 : return ccol_invalid_args;
324 : }
325 :
326 10 : size_t str_len = strlen(str);
327 10 : if (str_len == 0) {
328 : return ccol_success;
329 : }
330 :
331 9 : size_t new_len = s->length + str_len;
332 9 : if (new_len < s->length || !cstring_length_fits_with_terminator(new_len)) {
333 : return ccol_container_full;
334 : }
335 :
336 18 : ptrdiff_t alias_off =
337 9 : (str >= s->data && str < s->data + s->capacity) ? (str - s->data) : -1;
338 :
339 9 : if (!cstring_grow_to(s, new_len + 1)) {
340 : return ccol_not_enough_memory;
341 : }
342 :
343 8 : if (alias_off >= 0) {
344 4 : str = s->data + alias_off;
345 : }
346 :
347 8 : memmove(s->data + str_len, s->data, s->length + 1);
348 :
349 8 : if (alias_off > 0) {
350 2 : str = s->data + alias_off + str_len;
351 : }
352 :
353 8 : memmove(s->data, str, str_len);
354 8 : s->length = new_len;
355 :
356 8 : return ccol_success;
357 : }
358 :
359 : // Inserts str at byte pos (pos equal to the length appends). The buffer grows
360 : // before the memmove. str may point into s: Its offset is saved before the
361 : // buffer can move, shifted when it lies after pos, and the final copy is a
362 : // memmove because source and destination can overlap. Results as for
363 : // cstring_append(), plus ccol_invalid_args for pos past the end.
364 17 : ccol_retval cstring_insert(cstr s, size_t pos, const char *str) {
365 17 : if (!s) {
366 1 : ccol__assert(false);
367 : }
368 16 : if (!str || pos > s->length) {
369 : return ccol_invalid_args;
370 : }
371 :
372 14 : size_t str_len = strlen(str);
373 14 : if (str_len == 0) {
374 : return ccol_success;
375 : }
376 :
377 13 : size_t new_len = s->length + str_len;
378 13 : if (new_len < s->length || !cstring_length_fits_with_terminator(new_len)) {
379 : return ccol_container_full;
380 : }
381 :
382 26 : ptrdiff_t alias_off =
383 13 : (str >= s->data && str < s->data + s->capacity) ? (str - s->data) : -1;
384 :
385 13 : if (!cstring_grow_to(s, new_len + 1)) {
386 : return ccol_not_enough_memory;
387 : }
388 :
389 12 : if (alias_off >= 0) {
390 7 : str = s->data + alias_off;
391 : }
392 :
393 12 : memmove(s->data + pos + str_len, s->data + pos, s->length - pos + 1);
394 :
395 12 : if (alias_off >= 0 && (size_t)alias_off > pos) {
396 2 : str = s->data + alias_off + str_len;
397 : }
398 :
399 12 : memmove(s->data + pos, str, str_len);
400 12 : s->length = new_len;
401 :
402 12 : return ccol_success;
403 : }
404 :
405 : // Replaces the content of s with str, '\0' included. str may point into s, so
406 : // its offset is saved before a realloc and the copy is a memmove. Results as
407 : // for cstring_append().
408 14 : ccol_retval cstring_set(cstr s, const char *str) {
409 14 : if (!s) {
410 1 : ccol__assert(false);
411 : }
412 13 : if (!str) {
413 : return ccol_invalid_args;
414 : }
415 :
416 12 : size_t str_len = strlen(str);
417 12 : if (!cstring_length_fits_with_terminator(str_len)) {
418 : return ccol_container_full;
419 : }
420 :
421 24 : ptrdiff_t alias_off =
422 12 : (str >= s->data && str < s->data + s->capacity) ? (str - s->data) : -1;
423 :
424 12 : if (!cstring_grow_to(s, str_len + 1)) {
425 : return ccol_not_enough_memory;
426 : }
427 :
428 11 : if (alias_off >= 0) {
429 4 : str = s->data + alias_off;
430 : }
431 :
432 11 : memmove(s->data, str, str_len + 1);
433 11 : s->length = str_len;
434 :
435 11 : return ccol_success;
436 : }
437 :
438 : // Empties s and shrinks its buffer back to the minimum when it's larger; a
439 : // failed realloc keeps the old capacity. A string already at the minimum skips
440 : // the realloc. Asserts on a NULL s.
441 9 : void cstring_reset(cstr s) {
442 9 : if (!s) {
443 1 : ccol__assert(false);
444 : }
445 :
446 8 : if (s->capacity != cstring_minimum_capacity) {
447 3 : char *orig = s->data;
448 3 : s->data = (char *)ccol__mem_realloc(s->m_procs, s->data,
449 : cstring_minimum_capacity);
450 3 : if (!s->data) {
451 1 : s->data = orig;
452 : } else {
453 2 : s->capacity = cstring_minimum_capacity;
454 : }
455 : }
456 8 : s->length = 0;
457 8 : s->data[0] = '\0';
458 8 : }
459 :
460 : // Makes the buffer of s hold at least min_capacity bytes, so later appends
461 : // don't reallocate; a smaller request becomes the minimum. Gives the result of
462 : // cstring_grow_to(). Asserts on a NULL s.
463 13 : bool cstring_reserve(cstr s, size_t min_capacity) {
464 13 : if (!s) {
465 1 : ccol__assert(false);
466 : }
467 :
468 12 : size_t needed = min_capacity < cstring_minimum_capacity
469 : ? cstring_minimum_capacity
470 : : min_capacity;
471 12 : return cstring_grow_to(s, needed);
472 : }
473 :
474 : // Turns the ASCII lower-case letters of s into upper case in place. toupper()
475 : // follows LC_CTYPE, so under a Turkish or single-byte locale it would change
476 : // other bytes, a piece of UTF-8 among them; the ASCII fold never does. Asserts
477 : // on a NULL s.
478 7 : void cstring_to_upper(cstr s) {
479 7 : if (!s) {
480 1 : ccol__assert(false);
481 : }
482 55 : for (size_t i = 0; i < s->length; i++) {
483 80 : s->data[i] = (char)ccol_ascii_toupper((unsigned char)s->data[i]);
484 : }
485 6 : }
486 :
487 : // Turns the ASCII upper-case letters of s into lower case in place, in every
488 : // locale, for the reason given at cstring_to_upper(). Asserts on a NULL s.
489 7 : void cstring_to_lower(cstr s) {
490 7 : if (!s) {
491 1 : ccol__assert(false);
492 : }
493 57 : for (size_t i = 0; i < s->length; i++) {
494 85 : s->data[i] = (char)ccol_ascii_tolower((unsigned char)s->data[i]);
495 : }
496 6 : }
497 :
498 : // Removes the six ASCII white-space bytes at both ends of s in place, whatever
499 : // the locale, so a UTF-8 byte is never cut. The end goes first because it only
500 : // moves the '\0'; the start then needs one memmove. Asserts on a NULL s.
501 16 : void cstring_trim(cstr s) {
502 16 : if (!s) {
503 1 : ccol__assert(false);
504 : }
505 15 : if (s->length == 0) {
506 : return;
507 : }
508 :
509 41 : while (s->length > 0 &&
510 39 : ccol_ascii_isspace((unsigned char)s->data[s->length - 1])) {
511 27 : s->length--;
512 : }
513 14 : s->data[s->length] = '\0';
514 :
515 14 : size_t start = 0;
516 33 : while (start < s->length &&
517 31 : ccol_ascii_isspace((unsigned char)s->data[start])) {
518 19 : start++;
519 : }
520 14 : if (start > 0) {
521 6 : memmove(s->data, s->data + start, s->length - start + 1);
522 6 : s->length -= start;
523 : }
524 : }
525 :
526 : // Computes the length of a string of orig_length bytes after count (more than
527 : // 0) non-overlapping nlen-byte needles become rlen-byte replacements, for
528 : // cstring_replace(). Gives ccol_success with the length in *new_len_out, or
529 : // ccol_container_full when the product or the sum overflows or the result
530 : // leaves no room for the '\0'. A shrinking replace can't underflow, because
531 : // count * nlen is at most orig_length. It's a function of its own so the tests
532 : // can reach the overflow guards without strings of several gigabytes.
533 16 : static ccol_retval compute_replace_new_length(size_t orig_length, size_t nlen,
534 : size_t rlen, size_t count,
535 : size_t *new_len_out) {
536 16 : ccol__assert(count > 0);
537 :
538 16 : if (rlen >= nlen) {
539 12 : size_t added = (rlen - nlen) * count;
540 12 : if (added / count != (rlen - nlen)) {
541 : return ccol_container_full;
542 : }
543 11 : size_t new_len = orig_length + added;
544 11 : if (new_len < orig_length ||
545 10 : !cstring_length_fits_with_terminator(new_len)) {
546 : return ccol_container_full;
547 : }
548 9 : *new_len_out = new_len;
549 : } else {
550 4 : *new_len_out = orig_length - (nlen - rlen) * count;
551 : }
552 :
553 : return ccol_success;
554 : }
555 :
556 : // Replaces every non-overlapping needle in s with replacement. It counts the
557 : // matches first, so the new buffer is allocated once at its exact size, builds
558 : // the result there and swaps it in. Results as documented in cstring.h; s is
559 : // unchanged on failure. Asserts on a NULL s.
560 16 : ccol_retval cstring_replace(cstr s, const char *needle,
561 : const char *replacement) {
562 16 : if (!s) {
563 1 : ccol__assert(false);
564 : }
565 15 : if (!needle || needle[0] == '\0' || !replacement) {
566 : return ccol_invalid_args;
567 : }
568 :
569 12 : size_t nlen = strlen(needle);
570 12 : size_t rlen = strlen(replacement);
571 :
572 12 : size_t count = 0;
573 12 : const char *ptr = s->data;
574 32 : while ((ptr = strstr(ptr, needle)) != NULL) {
575 20 : count++;
576 20 : ptr += nlen;
577 : }
578 :
579 12 : if (count == 0) {
580 : return ccol_success;
581 : }
582 :
583 11 : size_t new_len;
584 11 : ccol_retval len_rv =
585 11 : compute_replace_new_length(s->length, nlen, rlen, count, &new_len);
586 11 : if (len_rv != ccol_success) {
587 : return len_rv;
588 : }
589 :
590 11 : size_t new_cap = ccol__find_nearest_gte_power_of_two(new_len + 1);
591 11 : if (new_cap == ccol_invalid_size) {
592 : return ccol_container_full;
593 : }
594 11 : if (new_cap < cstring_minimum_capacity) {
595 : new_cap = cstring_minimum_capacity;
596 : }
597 :
598 11 : char *new_buf = (char *)ccol__mem_alloc(s->m_procs, new_cap);
599 11 : if (!new_buf) {
600 : return ccol_not_enough_memory;
601 : }
602 :
603 10 : const char *src = s->data;
604 10 : char *dst = new_buf;
605 10 : const char *found;
606 28 : while ((found = strstr(src, needle)) != NULL) {
607 18 : size_t before = (size_t)(found - src);
608 18 : memcpy(dst, src, before);
609 18 : dst += before;
610 18 : memcpy(dst, replacement, rlen);
611 18 : dst += rlen;
612 18 : src = found + nlen;
613 : }
614 10 : size_t tail = strlen(src);
615 10 : memcpy(dst, src, tail + 1);
616 :
617 10 : ccol__mem_free(s->m_procs, s->data);
618 10 : s->data = new_buf;
619 10 : s->length = new_len;
620 10 : s->capacity = new_cap;
621 :
622 10 : return ccol_success;
623 : }
624 :
625 : // Compares s with str as strcmp() does; a NULL str gives 1, since a value is
626 : // greater than no value. Asserts on a NULL s.
627 8 : int cstring_compare(cstr s, const char *str) {
628 8 : if (!s) {
629 1 : ccol__assert(false);
630 : }
631 7 : if (!str) {
632 : return 1;
633 : }
634 6 : return strcmp(s->data, str);
635 : }
636 :
637 : // Says whether s holds exactly the bytes of str; a NULL str is not equal.
638 : // Asserts on a NULL s.
639 9 : bool cstring_equals(cstr s, const char *str) {
640 9 : if (!s) {
641 1 : ccol__assert(false);
642 : }
643 8 : if (!str) {
644 : return false;
645 : }
646 7 : return strcmp(s->data, str) == 0;
647 : }
648 :
649 : // Says whether s starts with prefix; a NULL prefix gives false and a prefix
650 : // longer than s is refused before any compare. Asserts on a NULL s.
651 9 : bool cstring_starts_with(cstr s, const char *prefix) {
652 9 : if (!s) {
653 1 : ccol__assert(false);
654 : }
655 8 : if (!prefix) {
656 : return false;
657 : }
658 7 : size_t plen = strlen(prefix);
659 7 : if (plen > s->length) {
660 : return false;
661 : }
662 6 : return strncmp(s->data, prefix, plen) == 0;
663 : }
664 :
665 : // Says whether s ends with suffix, comparing the tail in place; a NULL suffix
666 : // gives false. Asserts on a NULL s.
667 9 : bool cstring_ends_with(cstr s, const char *suffix) {
668 9 : if (!s) {
669 1 : ccol__assert(false);
670 : }
671 8 : if (!suffix) {
672 : return false;
673 : }
674 7 : size_t slen = strlen(suffix);
675 7 : if (slen > s->length) {
676 : return false;
677 : }
678 6 : return strncmp(s->data + s->length - slen, suffix, slen) == 0;
679 : }
680 :
681 : // Gives the offset of the first needle in s with strstr(), or ccol_invalid_size
682 : // when it's missing or needle is NULL. Asserts on a NULL s.
683 11 : size_t cstring_find(cstr s, const char *needle) {
684 11 : if (!s) {
685 1 : ccol__assert(false);
686 : }
687 10 : if (!needle) {
688 : return ccol_invalid_size;
689 : }
690 9 : const char *found = strstr(s->data, needle);
691 9 : if (!found) {
692 : return ccol_invalid_size;
693 : }
694 7 : return (size_t)(found - s->data);
695 : }
696 :
697 : #ifdef RUNNING_UNIT_TESTS
698 : // Counts the calls of cstring_rfind_linear(), so a test can prove that its
699 : // inputs reach that path with the table on the stack and on the heap.
700 : unsigned long cstring_rfind_linear_count_for_tests = 0;
701 : #endif
702 :
703 : // The longest needle whose failure table cstring_rfind_linear() keeps on the
704 : // stack; a longer one takes its table from the string's allocator.
705 : #define CSTRING_RFIND_STACK_TABLE_LEN 128
706 :
707 : // Gives the start of the rightmost needle that lies entirely inside hay[0,
708 : // limit), or ccol_invalid_size. The backward scan hands over to it when
709 : // candidates keep failing, because it bounds the search at O(limit + nlen) for
710 : // any text: It's Knuth-Morris-Pratt run right to left on the reversed needle.
711 : // The failure table takes one size_t per needle byte, from m_procs when it
712 : // doesn't fit on the stack; when that allocation fails it sets *table_ok to
713 : // false and searches nothing. Bumps the test counter.
714 : static __attribute__((noinline)) size_t
715 1737 : cstring_rfind_linear(const char *hay, size_t limit, const char *needle,
716 : size_t nlen, ccol_memmgmt_procs *m_procs, bool *table_ok) {
717 : #ifdef RUNNING_UNIT_TESTS
718 1737 : __atomic_fetch_add(&cstring_rfind_linear_count_for_tests, 1,
719 : __ATOMIC_RELAXED);
720 : #endif
721 1737 : size_t stack_table[CSTRING_RFIND_STACK_TABLE_LEN];
722 1737 : size_t *fail = stack_table;
723 1737 : if (nlen > CSTRING_RFIND_STACK_TABLE_LEN) {
724 2226 : fail = nlen <= SIZE_MAX / sizeof(size_t)
725 1112 : ? (size_t *)ccol__mem_alloc(m_procs, nlen * sizeof(size_t))
726 1112 : : NULL;
727 1112 : if (!fail) {
728 2 : *table_ok = false;
729 2 : return ccol_invalid_size;
730 : }
731 : }
732 1735 : *table_ok = true;
733 :
734 1735 : const size_t tail = nlen - 1;
735 1735 : fail[0] = 0;
736 1735 : size_t k = 0;
737 370939 : for (size_t q = 1; q < nlen; q++) {
738 520024 : while (k > 0 && needle[tail - q] != needle[tail - k]) {
739 150820 : k = fail[k - 1];
740 : }
741 369204 : if (needle[tail - q] == needle[tail - k]) {
742 225618 : k++;
743 : }
744 369204 : fail[q] = k;
745 : }
746 :
747 890686 : size_t found = ccol_invalid_size;
748 : size_t j = 0;
749 890686 : for (size_t i = limit; i-- > 0;) {
750 890596 : char c = hay[i];
751 1243224 : while (j > 0 && c != needle[tail - j]) {
752 352628 : j = fail[j - 1];
753 : }
754 890596 : if (c == needle[tail - j] && ++j == nlen) {
755 : found = i;
756 : break;
757 : }
758 : }
759 :
760 1735 : if (fail != stack_table) {
761 1110 : ccol__mem_free(m_procs, fail);
762 : }
763 : return found;
764 : }
765 :
766 : // The state of one backward scan of cstring_rfind(). charged counts the bytes
767 : // spent on candidates that failed, and budget is cleared once the hand-over to
768 : // cstring_rfind_linear() is known to be impossible.
769 : typedef struct {
770 : const char *hay;
771 : size_t length;
772 : const char *needle;
773 : size_t nlen;
774 : size_t charged;
775 : bool budget;
776 : ccol_memmgmt_procs *m_procs;
777 : } cstring_rfind_scan;
778 :
779 : // Tests the candidate at st, whose first and last bytes already match, for the
780 : // backward scan. Gives true with *result set once the answer is settled: st
781 : // matches, or the charge has passed four times the bytes scanned and
782 : // cstring_rfind_linear() answered for everything below st. Gives false when the
783 : // scan must go on. A failed table allocation turns the budget off, and the scan
784 : // finishes alone, which is always correct.
785 216279 : static inline bool cstring_rfind_candidate(cstring_rfind_scan *sc, size_t st,
786 : size_t *result) {
787 216279 : if (memcmp(sc->hay + st + 1, sc->needle + 1, sc->nlen - 2) == 0) {
788 5592 : *result = st;
789 5592 : return true;
790 : }
791 210687 : sc->charged += sc->nlen;
792 210687 : if (sc->budget && sc->charged > 4 * (sc->length - st)) {
793 1737 : bool table_ok;
794 1737 : size_t r = cstring_rfind_linear(sc->hay, st + sc->nlen - 1, sc->needle,
795 : sc->nlen, sc->m_procs, &table_ok);
796 1737 : if (table_ok) {
797 1735 : *result = r;
798 1735 : return true;
799 : }
800 2 : sc->budget = false;
801 : }
802 : return false;
803 : }
804 :
805 : // 16 bytes the compiler keeps in one vector register where the target has one.
806 : typedef unsigned char cstring_bytes16 __attribute__((vector_size(16)));
807 :
808 : // Tests the candidates in [b, b + 16) whose lanes are set in hit, from the
809 : // highest down, for the backward scan. Gives true with *result set when the
810 : // answer is settled.
811 82140 : static inline bool cstring_rfind_block(cstring_rfind_scan *sc, size_t b,
812 : cstring_bytes16 hit, size_t *result) {
813 82140 : unsigned char lanes[16];
814 82140 : memcpy(lanes, &hit, sizeof(lanes));
815 1313840 : for (size_t k = 16; k-- > 0;) {
816 1239013 : if (lanes[k] && cstring_rfind_candidate(sc, b + k, result)) {
817 : return true;
818 : }
819 : }
820 : return false;
821 : }
822 :
823 : // Says whether any lane of v is set, so the scan can skip a block in one test.
824 199045 : static inline bool cstring_bytes16_any(cstring_bytes16 v) {
825 199045 : uint64_t halves[2];
826 199045 : memcpy(halves, &v, sizeof(halves));
827 199045 : return (halves[0] | halves[1]) != 0;
828 : }
829 :
830 : // Below this length cstring_rfind() searches forward with strstr(); the
831 : // backward scan only pays off on longer strings.
832 : #define CSTRING_RFIND_SHORT 256
833 :
834 : // The backward search of cstring_rfind() for a string of at least
835 : // CSTRING_RFIND_SHORT bytes. It's out of line so the short path never pays for
836 : // its frame and vector setup. A one-byte needle is one memrchr(). Otherwise a
837 : // filter compares the needle's first byte against 16 start positions and its
838 : // last byte against the positions nlen - 1 further on, 64 positions per test,
839 : // and only a position that passes both gets a full compare. Gives the offset of
840 : // the last needle, the length for an empty needle, or ccol_invalid_size.
841 : static __attribute__((noinline)) size_t
842 10377 : cstring_rfind_backward(cstr s, const char *needle) {
843 10377 : size_t nlen = strlen(needle);
844 10377 : if (nlen == 0) {
845 552 : return s->length;
846 : }
847 9825 : if (nlen > s->length) {
848 : return ccol_invalid_size;
849 : }
850 9820 : if (nlen == 1) {
851 594 : const char *p =
852 594 : (const char *)cstring_memrchr(s->data, needle[0], s->length);
853 594 : return p ? (size_t)(p - s->data) : ccol_invalid_size;
854 : }
855 9226 : cstring_rfind_scan sc = {.hay = s->data,
856 : .length = s->length,
857 : .needle = needle,
858 : .nlen = nlen,
859 : .charged = 0,
860 : .budget = true,
861 9226 : .m_procs = s->m_procs};
862 9226 : const size_t tail = nlen - 1;
863 9226 : const unsigned char first = (unsigned char)needle[0];
864 9226 : const unsigned char last = (unsigned char)needle[tail];
865 9226 : const cstring_bytes16 vfirst = (cstring_bytes16){0} + first;
866 9226 : const cstring_bytes16 vlast = (cstring_bytes16){0} + last;
867 9226 : size_t result;
868 :
869 9226 : size_t pos = s->length - tail;
870 104633 : while (pos >= 16) {
871 102720 : if (pos >= 64) {
872 96890 : size_t b = pos - 64;
873 96890 : const char *pf = sc.hay + b;
874 96890 : const char *pl = pf + tail;
875 96890 : cstring_bytes16 f0, f1, f2, f3, l0, l1, l2, l3;
876 96890 : memcpy(&f0, pf, 16);
877 96890 : memcpy(&f1, pf + 16, 16);
878 96890 : memcpy(&f2, pf + 32, 16);
879 96890 : memcpy(&f3, pf + 48, 16);
880 96890 : memcpy(&l0, pl, 16);
881 96890 : memcpy(&l1, pl + 16, 16);
882 96890 : memcpy(&l2, pl + 32, 16);
883 96890 : memcpy(&l3, pl + 48, 16);
884 96890 : cstring_bytes16 any = (cstring_bytes16)(((f0 == vfirst) & (l0 == vlast)) |
885 96890 : ((f1 == vfirst) & (l1 == vlast)) |
886 96890 : ((f2 == vfirst) & (l2 == vlast)) |
887 96890 : ((f3 == vfirst) & (l3 == vlast)));
888 96890 : if (!cstring_bytes16_any(any)) {
889 565 : pos = b;
890 565 : continue;
891 : }
892 : }
893 102155 : size_t b = pos - 16;
894 102155 : cstring_bytes16 f, l;
895 102155 : memcpy(&f, sc.hay + b, sizeof(f));
896 102155 : memcpy(&l, sc.hay + b + tail, sizeof(l));
897 102155 : cstring_bytes16 hit = (cstring_bytes16)((f == vfirst) & (l == vlast));
898 102155 : if (cstring_bytes16_any(hit) && cstring_rfind_block(&sc, b, hit, &result)) {
899 7313 : return result;
900 : }
901 94842 : pos = b;
902 : }
903 16110 : while (pos-- > 0) {
904 14211 : if ((unsigned char)sc.hay[pos] == first &&
905 5877 : (unsigned char)sc.hay[pos + tail] == last &&
906 1471 : cstring_rfind_candidate(&sc, pos, &result)) {
907 14 : return result;
908 : }
909 : }
910 : return ccol_invalid_size;
911 : }
912 :
913 : // Gives the offset of the last needle in s, overlaps counted, or
914 : // ccol_invalid_size when it's missing or needle is NULL. A string of 256 bytes
915 : // or more goes straight to cstring_rfind_backward(); a shorter one is searched
916 : // forward with strstr(), which is faster at that length. Every failed candidate
917 : // of the backward filter is charged nlen, and past four times the bytes scanned
918 : // the rest goes to the linear search, so a text built to defeat the filter
919 : // costs O(n + m) all the same. Asserts on a NULL s.
920 20421 : size_t cstring_rfind(cstr s, const char *needle) {
921 20421 : if (!s) {
922 1 : ccol__assert(false);
923 : }
924 20420 : if (!needle) {
925 : return ccol_invalid_size;
926 : }
927 20419 : if (s->length >= CSTRING_RFIND_SHORT) {
928 10377 : return cstring_rfind_backward(s, needle);
929 : }
930 10042 : if (needle[0] == '\0') {
931 : return s->length;
932 : }
933 9512 : if (needle[1] == '\0') {
934 1171 : const char *p =
935 1171 : (const char *)cstring_memrchr(s->data, needle[0], s->length);
936 1171 : return p ? (size_t)(p - s->data) : ccol_invalid_size;
937 : }
938 8341 : size_t last = ccol_invalid_size;
939 8341 : const char *ptr = s->data;
940 8341 : const char *found;
941 67909 : while ((found = strstr(ptr, needle)) != NULL) {
942 59568 : last = (size_t)(found - s->data);
943 59568 : ptr = found + 1;
944 : }
945 : return last;
946 : }
947 :
948 : // Creates a string holding at most length bytes of s from start, clamped to the
949 : // end; a start past the end gives an empty string. It shares the allocator of
950 : // s. Gives NULL with *err set on failure. Asserts on a NULL s.
951 16 : cstr cstring_substring(cstr s, size_t start, size_t length, char **err) {
952 16 : if (!s) {
953 1 : ccol__assert(false);
954 : }
955 :
956 15 : if (start >= s->length) {
957 3 : return cstring_create_from_span(NULL, 0, s->m_procs, err);
958 : }
959 :
960 12 : size_t actual_len = ccol__min(length, s->length - start);
961 12 : return cstring_create_from_span(s->data + start, actual_len, s->m_procs, err);
962 : }
963 :
964 : // Creates an independent copy of s with the same allocator, or NULL with *err
965 : // set on failure. Asserts on a NULL s.
966 5 : cstr cstring_copy(cstr s, char **err) {
967 5 : if (!s) {
968 1 : ccol__assert(false);
969 : }
970 4 : return cstring_create_full(s->data, s->m_procs, err);
971 : }
972 :
973 : // Splits s at every delimiter into a cvec of new cstr, sharing the allocator of
974 : // s; there is always at least one token, the tail, which may be empty. Gives
975 : // NULL with *err set for a NULL or empty delimiter or a failed allocation,
976 : // after destroying every token made so far. Asserts on a NULL s.
977 17 : cvec cstring_split(cstr s, const char *delimiter, char **err) {
978 17 : if (!s) {
979 1 : ccol__assert(false);
980 : }
981 16 : if (!delimiter || delimiter[0] == '\0') {
982 2 : if (err) {
983 2 : *err = CCOL__ERR_STR("delimiter must be a non-empty string");
984 : }
985 2 : return NULL;
986 : }
987 :
988 14 : cvec result = cvector_create_full(sizeof(cstr), s->m_procs, err);
989 14 : if (!result) {
990 : return NULL;
991 : }
992 :
993 13 : size_t dlen = strlen(delimiter);
994 13 : const char *current = s->data;
995 13 : const char *found;
996 :
997 32 : while ((found = strstr(current, delimiter)) != NULL) {
998 20 : size_t part_len = (size_t)(found - current);
999 :
1000 20 : cstr part = cstring_create_from_span(current, part_len, s->m_procs, err);
1001 20 : if (!part) {
1002 1 : destroy_cstr_vector(result);
1003 1 : return NULL;
1004 : }
1005 :
1006 19 : ccol_retval rv = cvector_push_back(result, &part);
1007 19 : if (rv != ccol_success) {
1008 0 : cstring__destroy(part);
1009 0 : destroy_cstr_vector(result);
1010 0 : if (err) {
1011 0 : *err = CCOL__ERR_STR("failed to push split token into result vector");
1012 : }
1013 0 : return NULL;
1014 : }
1015 :
1016 19 : current = found + dlen;
1017 : }
1018 :
1019 24 : cstr last = cstring_create_from_span(
1020 12 : current, s->length - (size_t)(current - s->data), s->m_procs, err);
1021 12 : if (!last) {
1022 2 : destroy_cstr_vector(result);
1023 2 : return NULL;
1024 : }
1025 :
1026 10 : ccol_retval rv = cvector_push_back(result, &last);
1027 10 : if (rv != ccol_success) {
1028 0 : cstring__destroy(last);
1029 0 : destroy_cstr_vector(result);
1030 0 : if (err) {
1031 0 : *err =
1032 : CCOL__ERR_STR("failed to push last split token into result vector");
1033 : }
1034 0 : return NULL;
1035 : }
1036 :
1037 10 : if (err) {
1038 2 : *err = NULL;
1039 : }
1040 : return result;
1041 : }
1042 :
1043 : #ifdef RUNNING_UNIT_TESTS
1044 : // Gives the buffer capacity of s, so the tests can check the growth rules.
1045 : // Asserts on a NULL s.
1046 51 : size_t cstring__get_capacity(cstr s) {
1047 51 : if (!s) {
1048 0 : ccol__assert(false);
1049 : }
1050 51 : return s->capacity;
1051 : }
1052 :
1053 : // Gives cstring_length_fits_with_terminator(length), so a test can drive that
1054 : // guard without a string that fills the address space.
1055 4 : bool cstring__length_fits_with_terminator_for_tests(size_t length) {
1056 4 : return cstring_length_fits_with_terminator(length);
1057 : }
1058 :
1059 : // Gives compute_replace_new_length() of its arguments, so a test can drive the
1060 : // overflow guards of cstring_replace() without huge strings.
1061 5 : ccol_retval cstring__replace_compute_new_length_for_tests(size_t orig_length,
1062 : size_t nlen,
1063 : size_t rlen,
1064 : size_t count,
1065 : size_t *new_len_out) {
1066 5 : return compute_replace_new_length(orig_length, nlen, rlen, count,
1067 : new_len_out);
1068 : }
1069 : #endif
|