CX Framework
Cross-platform C utility framework
Loading...
Searching...
No Matches
Core String Functions

Macros

#define strInit(o)   *(o) = NULL
 
#define strTemp(ps, maxlen)
 

Typedefs

typedef struct str_ref * string
 Opaque handle to a string object.
 
typedef const struct str_ref * strref
 Borrowed reference to a string.
 
typedef string * strhandle
 Pointer to a string variable.
 

Functions

void strReset (strhandle o, uint32 sizehint)
 
void strDup (strhandle o, strref s)
 
void strCopy (strhandle o, strref s)
 
void strClear (strhandle ps)
 
uint32 strLen (strref s)
 
void strSetLen (strhandle ps, uint32 len)
 
bool strEmpty (strref s)
 
void strDestroy (strhandle ps)
 
const char * strC (strref s)
 
const char * strPC (strhandle ps)
 
uint8 * strBuffer (strhandle ps, uint32 minsz)
 
uint32 strCopyOut (strref s, uint32 off, uint8 *buf, uint32 bufsz)
 
uint32 strCopyRaw (strref s, uint32 off, uint8 *buf, uint32 maxlen)
 

Detailed Description

Macro Definition Documentation

◆ strInit

#define strInit (   o)    *(o) = NULL

void strInit(string *o);

Initializes a string variable to empty/NULL

This is a convenience macro equivalent to setting the string to NULL. While not strictly required (direct assignment works), it provides clarity.

Parameters
oPointer to string variable to initialize

Example:

string s;
strInit(&s);
#define strInit(o)
Definition strbase.h:61

Definition at line 61 of file strbase.h.

◆ strTemp

#define strTemp (   ps,
  maxlen 
)
Value:
(*(ps)) = (string)stackAlloc(_strStackAllocSize(maxlen)); \
_strInitStack(ps, maxlen);
struct str_ref * string
Opaque handle to a string object.
Definition strbase.h:29

void strTemp(string *ps, uint32 maxlen);

Creates a stack-allocated temporary string

Allocates a string buffer on the stack for temporary use within the current scope. This is more efficient than heap allocation for short-lived strings.

IMPORTANT RESTRICTIONS:

  • Must NOT be returned from a function
  • Must NOT be stored beyond the current scope
  • MUST call strDestroy() before scope exit (even though stack-allocated)

String functions won't promote stack strings to ropes. If an operation needs more space than maxlen, the handle may be replaced with a heap-allocated string, which is why strDestroy() is required.

Maximum length is 65528 bytes. Larger sizes will fail.

Parameters
psPointer to string variable (will point to stack buffer)
maxlenMaximum string length in bytes (excluding null terminator)

Example:

string temp;
strTemp(&temp, 256); // Stack buffer for up to 256 bytes
// ... use temp ...
strDestroy(&temp); // Required even for stack strings
#define strTemp(ps, maxlen)
Definition strbase.h:356
void strDestroy(strhandle ps)

Definition at line 356 of file strbase.h.

Typedef Documentation

◆ strhandle

typedef string* strhandle

Pointer to a string variable.

Used as an output parameter for functions that modify or create strings. Must always point to a valid string variable (which may be NULL).

Definition at line 45 of file strbase.h.

◆ string

typedef struct str_ref* string

Opaque handle to a string object.

Strings use copy-on-write semantics with automatic reference counting. Multiple string variables can efficiently share the same underlying buffer.

CRITICAL: Always initialize to NULL or 0 before first use:

string s = 0;

Strings must be destroyed with strDestroy() when no longer needed.

Definition at line 29 of file strbase.h.

◆ strref

typedef const struct str_ref* strref

Borrowed reference to a string.

Used for passing strings as function arguments without transferring ownership. The referenced string must remain valid for the duration of the function call.

IMPORTANT: Never return a strref from a function in multi-threaded programs. This creates a race condition where the underlying string could be destroyed by another thread. Always use an output parameter with strDup() instead.

Definition at line 39 of file strbase.h.

Function Documentation

◆ strBuffer()

uint8 * strBuffer ( strhandle  ps,
uint32  minsz 
)

Returns a writable pointer to the string's buffer

Provides direct access to the string's internal buffer for modification. The string is automatically:

  • Flattened if it's a rope
  • Made unique if it has multiple references
  • Created if NULL
  • Grown and zero-padded if shorter than minsz

After calling this function, encoding flags are cleared since the buffer may be modified in ways that invalidate them.

The returned pointer is valid until the next string operation.

Parameters
psPointer to string variable
minszMinimum buffer size in bytes (string is grown/padded if needed)
Returns
Writable buffer pointer (at least minsz bytes available)

Example:

uint8 *buf = strBuffer(&s, 256);
memcpy(buf, data, 100);
strSetLen(&s, 100); // Update length after direct write
void strSetLen(strhandle ps, uint32 len)
uint8 * strBuffer(strhandle ps, uint32 minsz)

◆ strC()

const char * strC ( strref  s)

Returns a read-only C-style string pointer

Provides access to the string content as a null-terminated C string. For simple strings, returns a pointer to the internal buffer. For ropes, returns a scratch buffer with the flattened content.

IMPORTANT: Scratch buffers are temporary and may be overwritten by other operations (see cx/utils/scratch.h). Use or copy the result immediately. For a persistent pointer, use strPC() instead.

NULL input returns an empty string (not NULL).

Parameters
sString to access (NULL returns "")
Returns
Null-terminated C string (may be temporary for ropes)

Example:

printf("String: %s\n", strC(s));
const char * strC(strref s)

◆ strClear()

void strClear ( strhandle  ps)

Clears a string to empty while potentially preserving capacity

Sets the string length to zero but may retain the allocated buffer for future use. This is more efficient than destroying and recreating the string if you plan to reuse it. The encoding flags are reset to UTF-8/ASCII.

For strings that cannot be cleared in place (ropes, shared references, etc.), a new empty string is created instead.

Parameters
psPointer to string to clear

Example:

strClear(&s); // Now empty but may keep buffer
void strClear(strhandle ps)

◆ strCopy()

void strCopy ( strhandle  o,
strref  s 
)

Copies a string without using copy-on-write optimization

Always creates a new independent copy of the string, unlike strDup which may create a reference. Use this when you need to ensure the output has its own buffer that can be modified without needing to copy-on-write.

The output string is destroyed first if it already exists.

Parameters
oPointer to output string variable
sString to copy (NULL creates empty string)

Example:

string original = _S"shared";
string copy = 0;
strCopy(&copy, original); // Independent copy
void strCopy(strhandle o, strref s)
#define _S
Creates a static ASCII string from a string literal.
Definition strbase.h:392

◆ strCopyOut()

uint32 strCopyOut ( strref  s,
uint32  off,
uint8 *  buf,
uint32  bufsz 
)

Copies string content to an external buffer with null termination

Copies up to bufsz-1 bytes from the string starting at the specified offset, then adds a null terminator. The result is always a valid C string even if truncated.

If the offset is beyond the string length, an empty string is returned. If NULL string or zero buffer size, no copy is performed.

Parameters
sSource string (NULL returns 0)
offStarting offset in source string
bufDestination buffer
bufszSize of destination buffer (must be at least 1)
Returns
Number of bytes copied (excluding null terminator)

Example:

char buf[32];
uint32 copied = strCopyOut(s, 0, (uint8*)buf, sizeof(buf));
uint32 strCopyOut(strref s, uint32 off, uint8 *buf, uint32 bufsz)

◆ strCopyRaw()

uint32 strCopyRaw ( strref  s,
uint32  off,
uint8 *  buf,
uint32  maxlen 
)

Copies raw string bytes without null termination

Copies up to maxlen bytes from the string starting at the specified offset. Unlike strCopyOut(), this does NOT add a null terminator, making it suitable for binary data or when concatenating into a larger buffer.

If the offset is beyond the string length, nothing is copied.

Parameters
sSource string (NULL returns 0)
offStarting offset in source string
bufDestination buffer
maxlenMaximum number of bytes to copy
Returns
Number of bytes actually copied

Example:

uint8 buf[256];
uint32 n = strCopyRaw(s, 10, buf, 100); // Copy 100 bytes from offset 10
uint32 strCopyRaw(strref s, uint32 off, uint8 *buf, uint32 maxlen)

◆ strDestroy()

void strDestroy ( strhandle  ps)

Destroys a string and frees its resources

Decrements the reference count atomically. If this was the last reference, the string buffer is freed. The string variable is set to NULL.

Safe to call with NULL strings or strings not allocated by CX (which are simply discarded without freeing). Stack-allocated strings are not freed.

Always call this when done with a string to prevent memory leaks.

Parameters
psPointer to string to destroy (set to NULL after)

Example:

string s = _S"hello";
strDestroy(&s); // s is now NULL

◆ strDup()

void strDup ( strhandle  o,
strref  s 
)

Duplicates a string using copy-on-write optimization

Creates a reference to the source string when possible, avoiding copying. The reference count is incremented atomically for thread safety. If the source is not a CX-managed string, a plain C string, or a stack-allocated string, a copy is made instead.

Special case: If the output is a stack-allocated string, the content is copied into the stack buffer rather than replacing the handle.

The output string is destroyed first if it already exists.

Parameters
oPointer to output string variable
sString to duplicate (NULL creates empty string)

Example:

string s1 = 0;
strDup(&s1, _S"hello"); // Efficient reference
string s2 = 0;
strDup(&s2, s1); // Shares buffer with s1
void strDup(strhandle o, strref s)

◆ strEmpty()

bool strEmpty ( strref  s)

Tests if a string is empty or NULL

Returns true for NULL strings or strings with zero length. This is more efficient than comparing strLen() to zero for strings without cached length.

Parameters
sString to test (NULL returns true)
Returns
true if string is empty or NULL, false otherwise

Example:

if (strEmpty(s)) {
// Handle empty string case
}
bool strEmpty(strref s)

◆ strLen()

uint32 strLen ( strref  s)

Returns the length of a string in bytes

Returns the number of bytes in the string content, not including the null terminator or any preallocated but unused capacity. NULL strings have length 0.

This is a constant-time operation (O(1)) as the length is cached in the string header.

Parameters
sString to query (NULL returns 0)
Returns
Length in bytes (not character count for multi-byte encodings)

Example:

uint32 len = strLen(_S"hello"); // Returns 5
uint32 strLen(strref s)

◆ strPC()

const char * strPC ( strhandle  ps)

Returns a persistent read-only C-style string pointer

Similar to strC(), but guarantees the returned pointer remains valid as long as the string is not modified. This is the middle ground between strC() and strBuffer():

  • Unlike strC(): Pointer is persistent (not a scratch buffer)
  • Unlike strBuffer(): Buffer may be shared (read-only) Won't duplicate if already refcounted

For ropes, this flattens the string into a contiguous buffer, modifying the handle to point to the flattened version.

Parameters
psPointer to string variable (may be modified if rope)
Returns
Persistent null-terminated C string (valid until string is modified)

Example:

const char *persistent = strPC(&s);
// Can safely use 'persistent' as long as s isn't modified
const char * strPC(strhandle ps)

◆ strReset()

void strReset ( strhandle  o,
uint32  sizehint 
)

Creates a new empty string with preallocated storage

If the output string already exists, it is destroyed first. The new string is allocated with enough capacity for the specified size plus overhead. This is useful when you know approximately how large the string will grow.

The string is initialized with UTF-8 and ASCII encoding flags set.

Parameters
oPointer to string variable (existing string will be destroyed)
sizehintExpected string size in bytes (0 for default minimum)

Example:

string s = 0;
strReset(&s, 256); // Preallocate for ~256 byte string
void strReset(strhandle o, uint32 sizehint)

◆ strSetLen()

void strSetLen ( strhandle  ps,
uint32  len 
)

Sets the length of a string, growing or truncating as needed

If growing the string, the new space is zero-filled. If truncating, the string is shortened and null-terminated at the new length.

The string is flattened (if it's a rope) and made unique (if it has multiple references) before modification. If the buffer needs to grow, it is reallocated.

Parameters
psPointer to string to modify
lenNew length in bytes

Example:

strSetLen(&s, 10); // Set to exactly 10 bytes