Last active
February 20, 2019 05:17
-
-
Save pervognsen/85d6153c1b321969c49021a0a7ee23d9 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
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