Created
July 23, 2011 16:31
-
-
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
This file contains hidden or 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
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.