cstring · Overview
cstring
NAME
CSTRING - overview of the cstring dynamic string
LIBRARY
C Collections (libccollections, -lccollections)
SYNOPSIS
#include <ccollections/cstring.h>
DESCRIPTION
A cstr is a heap string that grows whenever an operation needs more space. Its buffer always holds a NUL-terminated C string, so you can pass the pointer from cstr_c_str(3) straight to any function that takes a const char *. A cstr holds text, and its content stops at the first NUL byte. The capacity of the buffer is always a power of two and never less than 16 bytes. An operation that needs more space grows the buffer to the smallest power of two that holds the result. cstr_reserve(3) grows it before you need the space, and cstr_reset(3) shrinks it back to 16 bytes. There are two layers in the API. The type-inferred macros, such as cstr_construct(3), cstr_append(3) and cstr_replace(3), stop the program through ccol__fatal_err() when an operation fails. The raw functions, such as cstring_create_full(3), cstring_append(3) and cstring_replace(3), report a failure in their return value instead. cstr_copy(3) and cstr_split(3) are the two macros that behave differently: They call their functions directly and give NULL on failure. Every argument that gives text to add is a plain C string. The calls that change a string (cstr_append(3), cstr_prepend(3), cstr_insert(3), cstr_set(3) and their cstring_ functions) accept a str argument that points into the buffer of that same string, as in cstr_append(s, cstr_c_str(s)), and they read str correctly even when they reallocate the buffer.
OWNERSHIP
The pointer from cstr_c_str(3) points into the buffer of the string. That buffer belongs to the string and you never free it. Any operation that changes the string can move the buffer, so the pointer is valid only until the next such operation. cstr_substring(3), cstr_copy(3) and cstr_split(3) give new strings that you own and must destroy. cstr_split(3) gives a cvec of cstr, so you destroy each element first and then the vector.
USE WITH THE MAPS
chashmap and cbstmap do not accept cstr as a key type or a value type; they accept char *, and they hash and compare such a key by its content. Give the result of cstr_c_str(3), cast to char *, as the key or the value. The map copies the characters into its own storage during the insert, so after the insert you can change or destroy the cstr without any effect on the map.
THREAD SAFETY
A string has no internal lock. You can share one string between threads, but then you must serialize every call that changes the string against all the other calls on that string.
EXAMPLES
#include <stdio.h> #include <ccollections/cstring.h> int main(void) { cstr_construct(path, "/var/log"); cstr_append(path, "/"); cstr_append(path, "app.log"); printf("%s (%zu)\n", cstr_c_str(path), cstr_length(path)); cstr_destroy(path); return 0; }
SEE ALSO
cstr_construct(3), cstr_c_str(3), cstr_append(3), cstr_split(3), cstring_create_full(3), cvector(7), chashmap(7)