Last active
July 18, 2022 03:14
-
-
Save pervognsen/012133e39129c935b8b7a1b0d100351c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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