diff options
| author | 3gg <3gg@shellblade.net> | 2023-02-17 08:51:24 -0800 |
|---|---|---|
| committer | 3gg <3gg@shellblade.net> | 2023-02-17 08:51:24 -0800 |
| commit | 0c1eb2535676a6fb2e1def08f9681b2a8b49f6e4 (patch) | |
| tree | 5bd623fe304be88b0ef3ebd6c8617a6705c529be | |
| parent | 75abeca4a9d606bee89a41475f2f451187fec127 (diff) | |
Add string hash.
| -rw-r--r-- | cstring/include/cstring.h | 14 |
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. | ||
| 110 | static 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 | ||
| 104 | DEF_STRING(sstring, 32) // Small. | 118 | DEF_STRING(sstring, 32) // Small. |
| 105 | DEF_STRING(mstring, 256) // Medium. | 119 | DEF_STRING(mstring, 256) // Medium. |
