burkey.co /docs/libflint/string
index string
~/docs/libflint/string.md
libflint

String

libflint·Utilities

C string helpers. LfStr is a counted view and does not own p. Builders that return a new string allocate it on the heap, or in an arena when the name ends in _arena.

Usage#

A view borrows bytes and does not add a terminator. lfstr_trim allocates a C string.

LfStr text = lfstr_trim_view(lfstr_from("  hello  "));
/* text.n == 5; text.p points at the 'h' in the literal */
if (lfstr_starts_with_view(text, lfstr_from("he")) == 1) {
    char *owned = lfstr_trim("  hello  ");
    if (owned != NULL) {
        /* owned is "hello" */
        free(owned);
    }
}

Free heap strings with free. Free a heap lfstr_split result with lfstr_split_free. Do not free arena memory. It stays live until the arena is cleared, restored past the block, or freed. For every _arena builder that also has a heap twin, a NULL arena allocates on the heap and that result must be freed. lfstr_copy_arena has no heap twin. A NULL allocator returns -1.

Structs#

LfStr#

p is borrowed. Keep that storage alive for as long as the view is used. n is a byte count and may include interior NUL bytes. lfstr_from does not. It stops at the first NUL.

typedef struct {
    const char *p;
    size_t n;
} LfStr;

Functions#

lfstr_from / lfstr_trim_view / view predicates#

lfstr_from borrows a C string. lfstr_from(NULL) is {NULL, 0}.

lfstr_trim_view returns a view of the same bytes with leading and trailing whitespace removed. A byte is whitespace when isspace is true for its unsigned value, in the current C locale. If s.p is NULL, the result is {NULL, 0} and s is not read. Otherwise p points into s.p. n is the kept length and may be 0. Nothing is allocated and no terminator is written.

An empty prefix, suffix, or needle (n == 0) returns 1 and does not read either pointer. If that length is greater than 0 and either pointer is NULL, or the needle is longer than the text, the result is 0. Otherwise the bytes are compared.

LfStr lfstr_from(const char *s);
LfStr lfstr_trim_view(LfStr s);
int lfstr_starts_with_view(LfStr s, LfStr prefix);
int lfstr_ends_with_view(LfStr s, LfStr suffix);
int lfstr_contains_view(LfStr s, LfStr needle);

lfstr_find / lfstr_find_arena#

Finds every byte offset of needle in haystack, including overlaps. The search advances one byte, so "aaa" and "aa" yield {0, 1}. An empty needle matches every position, including one past the last byte: "abc" and "" yield {0, 1, 2, 3}. An empty haystack and an empty needle yield {0}. An empty haystack and a non-empty needle yield no matches.

*substrings must be NULL on entry. It receives a size_t array of the offsets. There is no sentinel. The caller frees a heap array with free. An arena array must not be freed. If nothing matches, *substrings stays NULL, *num_substrings is 0, and nothing is allocated.

Returns 0 on success. Returns 1 if *substrings is not NULL, and leaves *num_substrings unchanged. Returns -1 if haystack, needle, num_substrings, or substrings is NULL, and writes nothing. Returns -1 if the offset array's size overflows or allocation fails. On that failure *num_substrings is 0 and *substrings is NULL. haystack and needle are not modified.

int lfstr_find(const char *haystack, const char *needle,
               size_t *num_substrings, size_t **substrings);
int lfstr_find_arena(ArenaAllocator *arena, const char *haystack,
                     const char *needle, size_t *num_substrings,
                     size_t **substrings);
size_t n = 0;
size_t *subs = NULL;
if (lfstr_find("One two three two", "two", &n, &subs) == 0) {
    /* n == 2, subs[0] == 4, subs[1] == 14 */
    free(subs);
}

lfstr_substr / lfstr_substr_arena#

Copies len bytes starting at idx and appends a NUL. The input is unchanged. Returns NULL if str is NULL, if the range is not inside the C string, if len + 1 overflows size_t, or if allocation fails. idx == strlen(str) and len == 0 is inside the string and returns an allocated empty string. An idx so large that idx + len would wrap is outside and returns NULL.

char *lfstr_substr(const char *str, size_t idx, size_t len);
char *lfstr_substr_arena(ArenaAllocator *arena, const char *str,
                         size_t idx, size_t len);

lfstr_copy_arena#

Copies s.n bytes and writes one trailing NUL after them. The NUL is not part of out->n. A NUL in the middle is data. This is not lfstr_substr_arena, which measures a C string with strlen and cannot see past the first NUL.

Returns 0 on success. *out views the copied bytes. n == 0 stores a non-NULL empty C string and does not read p. Returns -1 without writing *out if allocator is NULL, out is NULL, n > 0 and p is NULL, n == SIZE_MAX (the extra NUL does not fit in size_t), or the arena cannot hold the block. A failed arena_malloc does not move the bump. Do not free the pointer. There is no heap fallback.

int lfstr_copy_arena(ArenaAllocator *allocator, LfStr s, LfStr *out);

lfstr_trim / lfstr_trim_arena#

Returns a new string with leading and trailing whitespace removed, using the same isspace rule as lfstr_trim_view. Interior whitespace stays. The input is unchanged. Returns NULL if str is NULL or allocation fails. An empty or all-whitespace input returns an allocated empty string, not NULL. For a borrow, use lfstr_trim_view.

char *lfstr_trim(const char *str);
char *lfstr_trim_arena(ArenaAllocator *arena, const char *str);

lfstr_join / lfstr_join_arena#

Joins count C strings with sep between elements, not before the first or after the last. count == 1 is a copy of that string. An empty sep inserts nothing. The inputs are unchanged.

sep must be non-NULL. When count is 0 its bytes are not read, strs may be NULL, and the result is an allocated empty string. Returns NULL if sep is NULL, if count is not 0 and strs is NULL, if any entry is NULL, if a length overflows size_t, or if allocation fails. Those failures allocate nothing.

char *lfstr_join(const char **strs, size_t count, const char *sep);
char *lfstr_join_arena(ArenaAllocator *arena, const char **strs,
                       size_t count, const char *sep);

lfstr_starts_with / lfstr_ends_with#

Return 1 if the C string has that prefix or suffix, and 0 otherwise. A NULL str or a NULL pattern returns 0, including when the other argument is empty. After that check, the view rules apply, so an empty pattern returns 1.

int lfstr_starts_with(const char *str, const char *prefix);
int lfstr_ends_with(const char *str, const char *suffix);

lfstr_replace / lfstr_replace_arena#

Replaces non-overlapping occurrences of old with replacement, scanning left to right. Each match consumes strlen(old) bytes, so "aaa" with "aa" matches once. An empty replacement deletes those matches. If old is empty or not found, the result is a copy of str. replacement must still be a non-NULL C string. Its bytes are not copied when old is empty. The input is unchanged.

Returns NULL if any argument is NULL, if a length overflows size_t, or if allocation fails. Failure allocates nothing.

char *lfstr_replace(const char *str, const char *old, const char *replacement);
char *lfstr_replace_arena(ArenaAllocator *arena, const char *str,
                          const char *old, const char *replacement);

lfstr_to_upper / lfstr_to_upper_arena / lfstr_to_lower / lfstr_to_lower_arena#

Return a new string. Each byte is passed to toupper or tolower as an unsigned char, in the current C locale. The input is unchanged. Returns NULL if str is NULL, if the length plus the trailing NUL overflows size_t, or if allocation fails. An empty input returns an allocated empty string.

char *lfstr_to_upper(const char *str);
char *lfstr_to_upper_arena(ArenaAllocator *arena, const char *str);
char *lfstr_to_lower(const char *str);
char *lfstr_to_lower_arena(ArenaAllocator *arena, const char *str);

lfstr_split / lfstr_split_arena / lfstr_split_free#

Splits str on delim. delim is one string, not a set of characters, and matches do not overlap. The delimiter is not kept. Leading, trailing, and adjacent delimiters produce empty parts. An empty str with a non-empty delimiter yields one empty part. An empty delimiter yields one copy of str. The array has *count entries and no NULL sentinel.

Returns NULL if str, delim, or count is NULL, and does not write *count. On a later failure the return is NULL and *count is 0. A heap failure frees the pointer array and any strings already stored in it. An arena failure does not. Those blocks stay in the arena until clear, restore, or free. Size overflow and allocation failure are failures. The input is unchanged.

lfstr_split_free frees each of the count strings and then the array. It is only for a heap result. lfstr_split_free(NULL, count) does nothing. Do not call it on an arena result.

char **lfstr_split(const char *str, const char *delim, size_t *count);
char **lfstr_split_arena(ArenaAllocator *arena, const char *str,
                         const char *delim, size_t *count);
void lfstr_split_free(char **parts, size_t count);

lfstr_contains#

Returns 1 if substr occurs in str, and 0 otherwise. A NULL argument returns 0. After that check, the view rule applies, so an empty substr returns 1.

int lfstr_contains(const char *str, const char *substr);

lfstr_hash / lfstr_hash_cb / lfstr_match#

FNV-1a 64-bit, narrowed to size_t. The offset basis is 14695981039346656037. For each byte, XOR it into the hash, then multiply by 1099511628211. There is no seed and no global. The value is computed as a 64-bit unsigned quantity and cast to size_t. A 32-bit size_t drops the high half. This is a table hash, not a stored digest. Only n bytes are read, so the view needs no trailing NUL. Two calls on the same view return the same value.

n == 0 returns the offset basis and does not read p, even when p is NULL. n > 0 and p == NULL returns 0 and does not dereference. There is no failure return. 0 is not a distinguished error.

lfstr_hash_cb(NULL) returns 0. Any other pointer addresses an LfStr. An empty LfStr hashes to the offset basis.

lfstr_match is a hash-map equality callback: 0 when equal, 1 otherwise. NULL and NULL return 0. NULL against a non-NULL pointer returns 1. Lengths are compared first. Both lengths 0 return 0 without reading p. Otherwise the bytes are compared. n > 0 with a NULL p returns 1 and does not read, including when both sides are that same view. Equal views have equal hashes.

Neither function allocates or writes through its arguments. A map that stores an LfStr must keep that key's bytes alive. These functions do not copy them. lf_intern copies bytes into its own storage and uses these callbacks.

size_t lfstr_hash(LfStr s);
size_t lfstr_hash_cb(const void *p);
int lfstr_match(const void *a, const void *b);