cf_sintern¶
Category: string
GitHub: cute_string.h
Stores unique, static copy of a string in a global string interning table.
| Parameters | Description |
|---|---|
s |
The string to insert into the global table. |
Return Value¶
Returns a static, unique, stable, read-only copy of the string. The pointer is stable until cf_sinuke is called.
Code Example¶
Using cf_sintern for fast string comparison and as hash table keys.
// Intern some strings.
const char* apple = cf_sintern("apple");
const char* banana = cf_sintern("banana");
const char* apple2 = cf_sintern("apple"); // Returns same pointer as first apple!
// Fast pointer comparison (no strcmp needed).
CF_ASSERT(apple == apple2);
CF_ASSERT(apple != banana);
// Use as hash table keys (cast pointer to uint64_t).
CF_MAP(int) prices = NULL;
map_set(prices, (uint64_t)apple, 100);
map_set(prices, (uint64_t)banana, 50);
int apple_price = map_get(prices, (uint64_t)cf_sintern("apple"));
CF_ASSERT(apple_price == 100);
map_free(prices);
Remarks¶
Only one copy of each unique string is stored. The purpose is primarily a memory optimization to reduce duplicate strings. You can not modify this string in any way. It is 100% immutable. Some major benefits come from placing strings into this table.
- You can hash returned pointers directly into hash tables (instead of hashing the entire string).
- You can simply compare pointers for equality, as opposed to comparing the string contents, as long as both strings came from this function.
- You may optionally call cf_sinuke to free all resources used by the global string table.
- This function is very fast if the string was already stored previously.