aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
author3gg <3gg@shellblade.net>2023-02-17 08:51:24 -0800
committer3gg <3gg@shellblade.net>2023-02-17 08:51:24 -0800
commit0c1eb2535676a6fb2e1def08f9681b2a8b49f6e4 (patch)
tree5bd623fe304be88b0ef3ebd6c8617a6705c529be
parent75abeca4a9d606bee89a41475f2f451187fec127 (diff)
Add string hash.
-rw-r--r--cstring/include/cstring.h14
1 files changed, 14 insertions, 0 deletions
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 @@
4#include <assert.h> 4#include <assert.h>
5#include <bsd/string.h> 5#include <bsd/string.h>
6#include <stdbool.h> 6#include <stdbool.h>
7#include <stdint.h>
7#include <stdio.h> 8#include <stdio.h>
8 9
9/// A fixed-size string. 10/// A fixed-size string.
@@ -99,7 +100,20 @@
99 assert(written >= 0); \ 100 assert(written >= 0); \
100 str.length = (size_t)written; \ 101 str.length = (size_t)written; \
101 return str; \ 102 return str; \
103 } \
104 \
105 static inline uint64_t STRING##_hash(STRING str) { \
106 return cstring_hash(str.str); \
107 }
108
109/// Return a hash of the given string.
110static inline uint64_t cstring_hash(const char* str) {
111 uint64_t hash = 0;
112 for (size_t i = 0; i < strlen(str); ++i) {
113 hash = (uint64_t)str[i] + (hash << 6) + (hash << 16) - hash;
102 } 114 }
115 return hash;
116}
103 117
104DEF_STRING(sstring, 32) // Small. 118DEF_STRING(sstring, 32) // Small.
105DEF_STRING(mstring, 256) // Medium. 119DEF_STRING(mstring, 256) // Medium.