English · 中文
Docs home › API reference: buffers & views
The core buffer and view API of include/sx_core.h: creation, state,
mutation, substrings, view navigation and trimming. Search, comparison and
splitting are in Search, compare and split. Behavior
statements come from the public headers, the implementation and the
tests/*.c boundary comments.
Headers and layers. Include the one public header:
#include <sx.h>sx.h includes sx_core.h (buffers, views, search, comparison) and
declares sx_split and sx_reg_*. Link with -lstringx. Every function
on this page is declared in sx_core.h; sx_raw.h is an internal
allocation/debug API, not part of the supported public interface.
One allocation per buffer. An sx_t handle owns one NUL-terminated
byte array: ptr[0 .. len-1] are the content bytes, ptr[len] is always
'\0', cap is the allocation size and cap >= len + 1. len counts
content bytes, so an embedded '\0' is data, not a terminator — the
model is binary-safe by construction.
Ownership.
| Value | Owner | Released with |
|---|---|---|
buffer from sx_new*, sx_dup, sx_substr |
caller | sx_free |
owned argument of sx_append, sx_write, sx_insert |
transferred to the library | nothing: the call frees it |
| buffer returned by an edit | the same handle as self |
one sx_free for the original handle |
sx_view_t |
none: it aliases a buffer | nothing; views are never freed |
array from sx_find_all* or sx_split |
caller | free (see api-search.md) |
Every edit returns self, so calls chain and the handle stays stable. The
backing array may move on growth: sx_buf_mut/sx_buf_view_mut pointers
become stale after any call that can reallocate and must be re-fetched. The
owned argument is consumed even when the edit itself fails: the call returns
NULL, frees the argument, and leaves self unchanged.
NULL and out of contract. Documented NULL handling:
sx_new_from_cstr(NULL) and sx_dup(NULL) return NULL; the owned
forms of sx_append, sx_write, sx_insert and all _cstr forms return
NULL and leave self untouched when their second argument is NULL.
Everything else dereferences its buffer or window: sx_free, sx_len,
sx_cap, sx_buf_mut, sx_view, the view navigation family and the edit
functions reject NULL handles, and sx_new_from_view, sx_buf_view_mut
and sx_view_* reject ref == NULL (sx_len_view only reads the stored
length). Out of contract — undefined behavior, not an error return:
a NULL handle or v.ref, a freed handle, an out-of-bounds view, a double
free, use after a consuming call, self as owned, and indices that
violate an entry below.
Sentinels.
| Situation | Value |
|---|---|
| allocation failure | NULL |
| rejected NULL operand (where documented) | NULL |
| "no view" | .ref == NULL |
| not found / no match (search page) | (size_t)-1 |
| no matches / refused split (search page) | NULL |
Sizes are int. sx_len, sx_len_view and sx_cap return int;
view fields and search offsets are size_t. Content over INT_MAX bytes
is outside the tested contract; cast to (size_t) when mixing, e.g.
fwrite(sx_buf_mut(h), 1, (size_t)sx_len(h), stdout).
Views are snapshots. sx_view_t {ref, offset, len} is the byte window
[offset, offset + len) inside the buffer behind ref; it copies nothing
and modifies nothing, and a valid window satisfies
offset + len <= len(ref). A later edit that reallocates or changes the
length invalidates it: re-derive views afterwards, and do not edit a
buffer while views into it (such as a sx_split array) are in use.
ref == NULL means "no view", not a usable buffer.
Capacity growth. sx_new starts at capacity 32; growth is geometric
(double, then +0x10000 at 64 KiB and above), and a debug build with
-DSX_FORCE_EXACT_RESERVE sizes every allocation exactly to need + 1.
Capacity never shrinks (sx_truncate and sx_clear keep it), and no
function promises spare capacity beyond its stated guarantee.
sx_t *sx_new(void);Creates an empty buffer of capacity 32 bytes.
- Parameters: none.
- Returns: a new buffer (
len == 0,cap == 32,ptr[0] == '\0'), orNULLon allocation failure. - Ownership: caller-owned; release with
sx_free. - Edge cases: only
cap >= 1is guaranteed; the exact 32-byte start is an implementation detail.
sx_t *sx_new_from_cstr(const char *s);Creates a buffer holding a copy of the C string s.
- Parameters:
s— NUL-terminated string, read withstrlen. - Returns: a new caller-owned buffer, or
NULLwhens == NULLor on allocation failure. - Ownership: caller-owned; release with
sx_free. - Edge cases:
strlensemantics — an embedded'\0'truncates the copy; usesx_new_from_viewfor binary content.
sx_t *sx_new_from_view(sx_view_t v);Copies a view's bytes into a new, independent buffer.
- Parameters:
v— source window;v.lenbytes atv.ref->ptr + v.offset. - Returns: a new caller-owned buffer, or
NULLon allocation failure. - Ownership: caller-owned; release with
sx_free. - Edge cases: byte-exact and binary-safe (embedded
'\0'bytes are copied); no aliasing — mutating either buffer never affects the other.v.ref == NULLor an out-of-bounds window is out of contract.
sx_t *sx_new_with_cap(size_t n);Creates an empty buffer with exactly n allocated bytes.
- Parameters:
n— total allocation size in bytes. - Returns: a new caller-owned buffer with
cap == nforn >= 1, orNULLon allocation failure. - Ownership: caller-owned; release with
sx_free. - Edge cases: one byte is reserved for the terminator, so at most
n - 1content bytes fit;n == 0still allocates one byte (cap == 1), so the handle is always valid.
sx_t *buf = sx_new_with_cap(64); /* room for 63 content bytes */
buf = sx_append_cstr(buf, "hello"); /* no reallocation */
sx_free(buf);sx_t *sx_dup(const sx_t *src);Creates a deep, independent copy of a buffer.
- Parameters:
src— source buffer. - Returns: a new caller-owned buffer with the same content, or
NULLwhensrc == NULLor on allocation failure. - Ownership: caller-owned; copy and source are freed separately with
sx_free. - Edge cases: binary-safe; in v0.5 the copy's capacity is
len + 1, not the source's capacity.
sx_t *src = sx_new_from_cstr("hello");
sx_t *copy = sx_dup(src); /* independent: free both */
sx_free(copy);
sx_free(src);void sx_free(sx_t *h);Releases a buffer: the content array and the handle.
- Parameters:
h— a live handle owned by the caller. - Returns: nothing.
- Ownership: consumes
h; every view andsx_buf_mutpointer into it becomes invalid. - Edge cases:
h == NULLis out of contract — the handle is dereferenced (the regex layer'ssx_reg_free(NULL)no-op does not generalize). Double free and use after free are out of contract.
int sx_len(sx_t *h);Returns the number of content bytes.
- Parameters:
h— buffer. - Returns:
len, counting embedded'\0'bytes; the terminator is never counted; the buffer is not modified. - Edge cases:
h == NULLis out of contract; the result is anint(see the size note above).
int sx_len_view(sx_view_t v);Returns the view's stored length.
- Parameters:
v— the view whose length is wanted. - Returns:
(int)v.len; the backing buffer is not inspected and the window is not validated. - Edge cases:
v.lenaboveINT_MAXis outside the tested contract; the "no view" sentinel (ref == NULL) haslen == 0.
int sx_cap(sx_t *h);Returns the total bytes allocated for the content array.
- Parameters:
h— buffer. - Returns:
cap, always at leastlen + 1(the single-NUL invariant); the buffer is not modified. - Edge cases:
h == NULLis out of contract; spare capacity beyondlen + 1depends on the growth policy and is not a contract.
char *sx_buf_mut(sx_t *h);Returns a mutable pointer to the content array.
- Parameters:
h— buffer. - Returns:
ptr;ptr[len] == '\0'at all times. - Ownership: borrowed; bytes inside
[0, len)may be rewritten without changinglen. - Edge cases: do not write at or beyond
lenwithout a length-changing call, and do not keep the pointer across any call that can reallocate (sx_append*,sx_write*,sx_insert*,sx_reserve, a growingsx_truncate).h == NULLis out of contract.
char *p = sx_buf_mut(buf);
p[0] = 'H'; /* len unchanged; p[len] must stay '\0' */char *sx_buf_view_mut(sx_view_t v);Returns a mutable pointer to the first byte of a view's window.
- Parameters:
v— view into a buffer. - Returns:
v.ref->ptr + v.offset. - Ownership: borrowed; writes reach the backing buffer.
- Edge cases: the pointer carries no length — pair it with
sx_len_view(v)and stay inside the window.v.ref == NULLor an out-of-bounds window is out of contract; the pointer is stale after the backing buffer reallocates.
sx_view_t word = sx_view_range(sx_view(buf), 6, 5);
char *w = sx_buf_view_mut(word); /* == sx_buf_mut(buf) + 6 */
w[0] = 'W';sx_view_t sx_view(const sx_t *h);Returns the whole-buffer view.
- Parameters:
h— buffer. - Returns:
{ref: h->ref, offset: 0, len: sx_len(h)}; the view aliaseshand is never freed. - Edge cases: zero-copy and read-only;
h == NULLis out of contract.
sx_t *sx_reserve(sx_t *self, size_t min_cap);Ensures room for at least min_cap content bytes plus the terminator.
- Parameters:
self— buffer;min_cap— content bytes that must fit without a later reallocation. - Returns:
selfon success (including a no-op request), orNULLon allocation failure. - Ownership:
selfis returned and stays caller-owned; content and length are preserved. - Edge cases: on success
cap >= min_cap + 1; a request the current capacity already satisfies does not shrink it. Capacity only grows —sx_truncateandsx_clearnever release it — and the backing array may move, so re-fetch allsx_buf_mutpointers.
buf = sx_reserve(buf, 4096); /* cap >= 4097 */sx_t *sx_append(sx_t *self, sx_t *owned);Appends another buffer's content, consuming that buffer.
- Parameters:
self— destination;owned— source buffer. - Returns:
self, orNULLwhenowned == NULLor on allocation failure. - Ownership: ownership transfer — the call copies
owned's content and freesowned; do not use or free it afterwards. - Edge cases: byte-exact by content length, so embedded
'\0'bytes are appended;owned == NULLchanges nothing;selfmay reallocate; passingselfasownedis out of contract (it would be freed in use).
sx_t *sx_append_cstr(sx_t *self, const char *s);Appends a C string.
- Parameters:
self— destination;s— NUL-terminated source. - Returns:
self, orNULLwhens == NULLor on allocation failure. - Ownership: none;
sis only read. - Edge cases:
strlensemantics — an embedded'\0'truncates the appended bytes; appending""is a no-op returningself.
sx_t *sx_append_view(sx_t *self, sx_view_t v);Appends a view's bytes.
- Parameters:
self— destination;v— source window;v.lenbytes atv.ref->ptr + v.offset. - Returns:
self, orNULLon allocation failure. - Ownership: none;
vis only read. - Edge cases: byte-exact and binary-safe;
vmay aliasself, including when the append grows the buffer — in-place doubling withsx_append_view(h, sx_view(h))is supported.v.ref == NULLor an out-of-bounds window is out of contract.
buf = sx_append_view(buf, sx_view(buf)); /* doubles in place */sx_t *sx_write(sx_t *self, size_t idx, sx_t *owned);Overwrites bytes at idx, growing the length if needed, and consumes the
source buffer.
- Parameters:
self— destination;idx— first byte to overwrite;owned— source buffer. - Returns:
self;NULLwhenowned == NULL, when the write range cannot be reserved, or on allocation failure. - Ownership: ownership transfer — the content is copied and
ownedis freed; do not use or free it afterwards.ownedis freed even if the write fails. - Edge cases:
len' = max(len, idx + owned.len)— a write never shrinks the buffer.idx == lenis an append;idx < lenoverwrites in place;idx > lenextends and[len, idx)is unspecified. Ifidx + noverflowssize_t, or the resulting end cannot be reserved (a total content length ofSIZE_MAXcannot include a terminator), the call returnsNULLbefore copying and leavesselfunchanged. Passingselfasownedis out of contract.
buf = sx_new_from_cstr("abc");
buf = sx_write_cstr(buf, 6, "XY"); /* len 8; bytes 3..5 unspecified */sx_t *sx_write_cstr(sx_t *self, size_t idx, const char *s);Writes a C string at idx.
- Parameters:
self— destination;idx— first byte to write;s— NUL-terminated source. - Returns:
self;NULLwhens == NULL, when the write range cannot be reserved, or on allocation failure. - Ownership: none;
sis only read. - Edge cases:
strlensemantics (an embedded'\0'truncates the written bytes); ons == NULL,selfis untouched. The same range validation, padding andidxrules assx_writeapply.
sx_t *sx_write_view(sx_t *self, size_t idx, sx_view_t v);Writes a view's bytes at idx.
- Parameters:
self— destination;idx— first byte to write;v— source window. - Returns:
self;NULLwhen the write range cannot be reserved or on allocation failure. - Ownership: none;
vis only read. - Edge cases: byte-exact and binary-safe;
vmay aliasself, including when the write must grow the buffer (the source bytes survive the reservation). The overflow check runs before the alias-preserving pre-reserve, so a rejected range cannot change the target's capacity. Sameidx/padding rules assx_write; an out-of-bounds window is out of contract.
sx_t *sx_insert(sx_t *self, size_t idx, sx_t *owned);Inserts another buffer's content at idx, shifting the tail right, and
consumes that buffer.
- Parameters:
self— destination;idx— insertion point with0 <= idx <= len;owned— source buffer. - Returns:
self, orNULLwhenowned == NULLor on allocation failure. - Ownership: ownership transfer — the content is copied and
ownedis freed; do not use or free it afterwards. - Edge cases: the result is
[0, idx)++ inserted bytes ++[idx, len), withlen' = len + n;idx == lenis append-like.idx > lenis out of contract (the tail shift underflows), and passingselfasownedis out of contract.
buf = sx_insert_cstr(buf, 3, "-"); /* shift the tail right */sx_t *sx_insert_cstr(sx_t *self, size_t idx, const char *s);Inserts a C string at idx.
- Parameters:
self— destination;idx— insertion point with0 <= idx <= len;s— NUL-terminated source. - Returns:
self, orNULLwhens == NULLor on allocation failure. - Ownership: none;
sis only read. - Edge cases:
strlensemantics; ons == NULL,selfis untouched.idx > lenis out of contract.
sx_t *sx_insert_view(sx_t *self, size_t idx, sx_view_t v);Inserts a view's bytes at idx.
- Parameters:
self— destination;idx— insertion point with0 <= idx <= len;v— source window. - Returns:
self, orNULLon allocation failure. - Ownership: none;
vis only read. - Edge cases: byte-exact and binary-safe;
vmay aliasself, including when the insert grows the buffer, as long as its window starts at or beforeidx(the tested case: a slice taken at the insertion point). A self-aliased window starting afteridxlies in the region the tail shift overwrites and is out of contract — copy it first withsx_new_from_view.idx > lenand out-of-bounds views are out of contract.
sx_t *sx_truncate(sx_t *self, size_t new_len);Sets the content length to new_len.
- Parameters:
self— buffer;new_len— the new length in content bytes. - Returns:
selfon success;NULLon allocation failure while growing. - Edge cases: a shorter
new_lenkeeps the prefix and drops the tail; the samenew_lenis a no-op. A longernew_lengrows the buffer:lenbecomesnew_len,ptr[new_len] == '\0', and[old_len, new_len)is unspecified — do not read it until overwritten. A shrink does not reduce capacity.
sx_t *sx_erase(sx_t *self, size_t idx, size_t n);Removes n bytes at idx, shifting the tail left.
- Parameters:
self— buffer;idx— first byte to remove;n— number of bytes to remove. - Returns:
self;selfitself must be valid. - Edge cases:
idx + n == lenerases the suffix;idx + n > lenis a no-op returningselfunchanged;n == 0is a no-op. No allocation happens, so the call cannot fail. Anidx + noverflowingsize_tis out of contract.
buf = sx_erase(buf, 2, 100); /* idx+n > len: no-op, returns self */sx_t *sx_clear(sx_t *self);Empties the buffer, keeping its capacity.
- Parameters:
self— buffer. - Returns:
self(still caller-owned). - Edge cases: sets
len = 0andptr[0] = '\0'; the allocation and its capacity are kept, so the buffer is immediately reusable.
buf = sx_clear(buf); /* len 0, capacity kept */sx_t *sx_substr(const sx_t *h, size_t idx, size_t n);Copies [idx, idx + n) into a new, independent buffer.
- Parameters:
h— source buffer;idx— start offset;n— number of bytes, with the preconditionidx + n <= len(h). - Returns: a new caller-owned buffer, or
NULLon allocation failure. (A NULLhor out-of-bounds range is out of contract, not an error value.) - Ownership: caller-owned; release with
sx_free. - Edge cases:
n == 0yields an empty buffer; byte-exact and binary-safe, including embedded'\0'bytes. Unlike view navigation, this copies: mutations on either side never affect the other.
sx_t *word = sx_substr(buf, 6, 5); /* a copy, not a view */
sx_free(word);All four functions re-derive the (offset, len) window over an existing
buffer. None copies, modifies or transfers ownership; each returns a new
view value. Inputs must be valid views (ref != NULL, window inside
the buffer); invalid input is out of contract.
sx_view_t sx_view_advance(sx_view_t v, size_t n);Moves the window start right by n.
- Parameters:
v— input view;n— bytes to advance. - Returns: the adjusted view over the same buffer.
- Edge cases: with
H = len(ref):- if
offset + len + n < H, the end is kept andlenshrinks byn; - otherwise, if
offset + n < H, the start becomesoffset + nand the end clamps to the buffer end (len = H - offset); - otherwise the result is the empty view
(H, 0). It never moves past the buffer end, even for a largen; advancing a sub-view beyond its own end widens it to the buffer end (second case).
- if
sx_view_t rest = sx_view_advance(sx_view(buf), 2); /* start +2 */sx_view_t sx_view_retreat(sx_view_t v, size_t n);Moves the window start left by n, keeping the end fixed.
- Parameters:
v— input view;n— bytes to retreat. - Returns: the adjusted view over the same buffer.
- Edge cases:
lengrows by the amount the offset shrinks; the move saturates at offset 0 (lenbecomes the originaloffset + len), so the window never starts before the buffer.
sx_view_t sx_view_shift(sx_view_t v, ptrdiff_t off);Moves the window by a signed offset, preserving its length.
- Parameters:
v— input view;off— signed byte offset. - Returns: the adjusted view over the same buffer.
- Edge cases:
lenis preserved (unlike advance/retreat). A positiveoffthat would push the end past the buffer clamps tooffset = H - len(the window ends at the buffer end); a negativeoffsaturates the start at 0. On an empty buffer the result is(0, 0).
sx_view_t sx_view_range(sx_view_t v, size_t off, size_t len);Re-anchors the window at absolute coordinates, ignoring the input view's offset and length.
- Parameters:
v— supplies only the backing buffer;off— absolute start offset, with the preconditionoff <= H;len— requested length. - Returns: the view
(off, min(len, H - off)). - Edge cases: the length clamps to the buffer end;
off == Hgives(H, 0);off > His out of contract (H - offunderflows).
sx_view_t slice = sx_view_range(sx_view(buf), 2, 3); /* absolute (2, 3) */The trim family removes ASCII whitespace from a view's edges. The set is
exactly {space, '\t', '\v', '\f', '\r', '\n'}. No bytes are modified,
no ownership is transferred, and only bytes inside the window are
inspected.
sx_view_t sx_view_trim(sx_view_t v);Trims both edges of the view.
- Parameters:
v— input view. - Returns: the view with leading and trailing whitespace removed.
- Edge cases: equivalent to
sx_view_trim_back(sx_view_trim_front(v)). A view with no edge whitespace is returned unchanged. An all-whitespace view becomes the empty view at the window's end (offsetoffset + len, length 0) —(H, 0)for a whole-buffer view.
sx_view_t field = sx_view_trim(sx_view(buf)); /* strip ASCII whitespace */sx_view_t sx_view_trim_front(sx_view_t v);Drops leading whitespace.
- Parameters:
v— input view. - Returns: the view with leading whitespace removed.
- Edge cases: the offset moves right and
lenshrinks by the same amount, so the window end stays fixed. The scan is bounded by the view's own length and never runs past the window's end, even when whitespace continues in the buffer after it.
sx_view_t sx_view_trim_back(sx_view_t v);Drops trailing whitespace.
- Parameters:
v— input view. - Returns: the view with trailing whitespace removed.
- Edge cases: only the window's last byte (
offset + len - 1) is inspected andlenshrinks leftwards; the offset is unchanged, so an all-whitespace window becomes(offset, 0). Bytes outside the window are never examined.
This program builds a string, trims a view of it, copies the trimmed window into a new buffer, edits that buffer in place, and releases both buffers:
#include <sx.h>
#include <stdio.h>
int main(void) {
sx_t *h = sx_new_from_cstr(" hello, world ");
sx_view_t trimmed = sx_view_trim(sx_view(h)); /* (2, 12) */
sx_t *clean = sx_new_from_view(trimmed); /* independent copy */
clean = sx_append_cstr(clean, "!");
clean = sx_insert_cstr(clean, 0, "> ");
printf("%s (%d bytes)\n", sx_buf_mut(clean), sx_len(clean));
sx_free(clean);
sx_free(h);
return 0;
}Expected output:
> hello, world! (15 bytes)