Skip to content

Instantly share code, notes, and snippets.

@jedisct1
Created July 23, 2011 16:31
Show Gist options
  • Save jedisct1/1101607 to your computer and use it in GitHub Desktop.
Save jedisct1/1101607 to your computer and use it in GitHub Desktop.
Faster version of the djb2 hash by making gcc recognize it is deterministic
uint32_t djb_hash(const char * const key, size_t keylen)
{
uint32_t j = (uint32_t) 5381U;
const unsigned char *ukey = (const unsigned char *) key;
size_t i = (size_t) 0U;
if (keylen >= (size_t) 8U) {
const size_t keylen_chunk = keylen - 8U;
while (i <= keylen_chunk) {
const unsigned char * const p = ukey + i;
i += (size_t) 8U;
j = j * 33U ^ p[0]; j = j * 33U ^ p[1];
j = j * 33U ^ p[2]; j = j * 33U ^ p[3];
j = j * 33U ^ p[4]; j = j * 33U ^ p[5];
j = j * 33U ^ p[6]; j = j * 33U ^ p[7];
}
}
while (i < keylen) {
j = j * 33U ^ ukey[i++];
}
j &= 0xffffffff;
return j;
}
@jedisct1
Copy link
Author

j &= 0xffffffff is stripped out by the compiler if uint32_t is an exact 32-bit type as it should, and not a larger typedef'd type. It's only here for pure paranoia.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment