Last active
January 2, 2019 13:02
-
-
Save justinbowes/6258550 to your computer and use it in GitHub Desktop.
Hash strings at compile time.
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
#ifndef compile_time_hash_h | |
#define compile_time_hash_h | |
// Posted by jbowes. Public domain. | |
// source: (dead link) | |
// http://lol.zoy.org/blog/2011/12/20/cpp-constant-string-hash | |
// | |
// At higher compiler optimization levels (-O1 and higher on clang/llvm), | |
// C_HASH("string") should be replaced by a hash of "string" at compile time. | |
#include <string.h> | |
#include <stdint.h> | |
#define H1(s,i,x) (x * 65599u + (uint8_t)s[(i) < strlen(s) ? strlen(s) - 1 - (i) : strlen(s)]) | |
#define H4(s,i,x) H1(s, i, H1(s, i + 1, H1(s, i + 2, H1(s, i + 3, x)))) | |
#define H16(s,i,x) H4(s, i, H4(s, i + 4, H4(s, i + 8, H4(s, i + 12, x)))) | |
#define H64(s,i,x) H16(s, i, H16(s, i + 16, H16(s, i + 32, H16(s, i + 48, x)))) | |
#define H256(s,i,x) H64(s, i, H64(s, i + 64, H64(s, i + 128, H64(s, i + 192, x)))) | |
// Replace H16 if you want to handle longer strings, but you may | |
// run into your preprocessor's recursion limit. | |
// 17 is just a prime factor. | |
#define C_HASH(s) ((uint32_t)(H16(s,0,31))) | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment