Skip to content

Instantly share code, notes, and snippets.

@pervognsen
Last active February 20, 2019 05:17
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 pervognsen/85d6153c1b321969c49021a0a7ee23d9 to your computer and use it in GitHub Desktop.
Save pervognsen/85d6153c1b321969c49021a0a7ee23d9 to your computer and use it in GitHub Desktop.
struct NameNode {
len: uint32;
buf: char[1];
}
struct NameMap {
nodes: {uint64, NameNode*}[];
collisions: NameNode*[];
}
func namemap_getn(names: NameMap*, buf: char const*, len: usize): char const* {
#assert(len <= UINT32_MAX);
h := hash(buf, len);
i := hget(names.nodes, h);
if (i != alen(names.nodes)) {
if (node := names.nodes[i][1]; node.len == len && memcmp(node.buf, buf, len) == 0) {
return node.buf;
}
for (k := 0; k < alen(names.collisions); k++) {
if (node := names.collisions[k]; node.len == len && memcmp(node.buf, buf, len) == 0) {
return node.buf;
}
}
}
node: NameNode* = malloc(offsetof(NameNode, buf) + len + 1);
node.len = len;
memcpy(node.buf, buf, len);
node.buf[len] = 0;
if (i != alen(names.nodes)) {
apush(names.collisions, node);
} else {
hput(names.nodes, h, node);
}
return node.buf;
}
func namemap_get(names: NameMap*, str: char const*): char const* {
return namemap_getn(names, str, strlen(str));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment