From 0c1eb2535676a6fb2e1def08f9681b2a8b49f6e4 Mon Sep 17 00:00:00 2001 From: 3gg <3gg@shellblade.net> Date: Fri, 17 Feb 2023 08:51:24 -0800 Subject: Add string hash. --- cstring/include/cstring.h | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'cstring/include') diff --git a/cstring/include/cstring.h b/cstring/include/cstring.h index 75a5388..de85b43 100644 --- a/cstring/include/cstring.h +++ b/cstring/include/cstring.h @@ -4,6 +4,7 @@ #include #include #include +#include #include /// A fixed-size string. @@ -99,7 +100,20 @@ assert(written >= 0); \ str.length = (size_t)written; \ return str; \ + } \ + \ + static inline uint64_t STRING##_hash(STRING str) { \ + return cstring_hash(str.str); \ + } + +/// Return a hash of the given string. +static inline uint64_t cstring_hash(const char* str) { + uint64_t hash = 0; + for (size_t i = 0; i < strlen(str); ++i) { + hash = (uint64_t)str[i] + (hash << 6) + (hash << 16) - hash; } + return hash; +} DEF_STRING(sstring, 32) // Small. DEF_STRING(mstring, 256) // Medium. -- cgit v1.2.3