Skip to content

Instantly share code, notes, and snippets.

@pervognsen
Last active July 18, 2022 03:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pervognsen/012133e39129c935b8b7a1b0d100351c to your computer and use it in GitHub Desktop.
Save pervognsen/012133e39129c935b8b7a1b0d100351c to your computer and use it in GitHub Desktop.
typedef struct intern_t {
intern_t *next;
uint32_t length; // can be narrower if you want to limit internable string length, which is a good idea.
char str[1];
} intern_t;
hashtable_t string_table;
const char *string_intern(const char *str, uint32_t length) {
uint64_t key = string_hash(str, length);
intern_t *head = hashtable_get(string_table, key);
for (intern_t *node = head; node; node = node->next) {
if (length == node->length && strncmp(str, node->str, length) == 0)
return node->str;
}
intern_t *new_head = malloc(sizeof(intern_t *) + sizeof(uint32_t) + length + 1);
new_head->next = head;
new_head->length = length;
memcpy(new_head->str, str, length);
new_head->str[length] = 0;
hashtable_put(string_table, key, new_head);
return new_head->str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment