Home Rumble Youtube Twitter/X Kofi Contact / Crypto

String Internment

Hash table-based permanent string internment. There is no way to remove strings from the table, though the entire table can be allocated or destroyed all at once. You can have multiple independent tables if desired, such as a unique table for a parser instance.

Interned strings with the same contents have the same pointer. There is no need to call strcmp(), you can just compare the pointers themselves. Further, there is only one copy of the memory regardless of how many times a particular string is interred.

The internal type of the table itself is not exposed: struct string_internment_table; typedef struct string_internment_table string_internment_table_t;

There is a global pointer to an internment table. Users must provide and initialize the table it points to. extern string_internment_table_t* global_string_internment_table;

void string_internment_table_init(string_internment_table_t** ptab)
Allocates and initialized internal structures. ptab is filled with a pointer to the newly allocated table. Strings cannot be interred in a table before calling this function.
void string_internment_table_destroy(string_internment_table_t* tab)
Frees all memory related to the table, including all the strings held inside.
char* strint_(string_internment_table_t* tab, char* s); #define strint(a) strint_(global_string_internment_table, (a))
O(1) amortized
Places the string into the table and returns a permanent, unique pointer to the string. Subsequent calls with the same string contents will return the same pointer.
char* strnint_(string_internment_table_t* tab, char* s, size_t slen); #define strnint(a, b) strnint_(global_string_internment_table, (a), (b))
O(1) amortized
Places the string up to slen into the table and returns a permanent, unique pointer to the string. Subsequent calls with the same string contents will return the same pointer.