Skip to content

Instantly share code, notes, and snippets.

@cls
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cls/e5ed358248272553d981 to your computer and use it in GitHub Desktop.
Save cls/e5ed358248272553d981 to your computer and use it in GitHub Desktop.
Interning strings with a prefix tree
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char *
intern(const char *s)
{
union tree {
const char *str;
union tree *sub;
};
static union tree root;
union tree *node = &root;
const char *p = s;
do {
if(!node->sub) {
node->sub = calloc(1 << CHAR_BIT, sizeof *node->sub);
if(!node->sub)
return NULL;
}
node = &node->sub[(unsigned char)*p];
} while(*p++);
if(!node->str)
node->str = strdup(s);
return node->str;
}
int
main(int argc, char **argv)
{
int i;
const char *s;
for(i = 1; i < argc; i++) {
s = intern(argv[i]);
if(!s) {
perror(argv[0]);
return 1;
}
printf("%p: %s\n", (void *)s, s);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment