machinatrix
A very silly Matrix bot written in C
Loading...
Searching...
No Matches
hash.h
1#ifndef MACHINATRIX_HASH_H
2#define MACHINATRIX_HASH_H
3
4#include <stddef.h>
5#include <stdint.h>
6
7#define MTRIX_HASHER_INIT ((struct mtrix_hasher){.h = 0x1505})
8
9typedef uint64_t mtrix_hash;
10
14 mtrix_hash h;
15};
16
18static inline struct mtrix_hasher mtrix_hasher_add(
19 struct mtrix_hasher h, char b);
20
22static inline struct mtrix_hasher mtrix_hasher_add_str(
23 struct mtrix_hasher h, const char *s);
24
26static inline struct mtrix_hasher mtrix_hasher_add_bytes(
27 struct mtrix_hasher h, const void *p, size_t n);
28
30static inline mtrix_hash mtrix_hash_str(const char *s);
31
33static inline int mtrix_hash_cmp(const void *lhs, const void *rhs);
34
35struct mtrix_hasher mtrix_hasher_add(struct mtrix_hasher h, char b) {
36 return (struct mtrix_hasher){.h = ((h.h << 5) + h.h) + (uint64_t)b};
37}
38
39struct mtrix_hasher mtrix_hasher_add_str(
40 struct mtrix_hasher h, const char *s
41) {
42 for(char c; (c = *s++);)
43 h = mtrix_hasher_add(h, c);
44 return h;
45}
46
47struct mtrix_hasher mtrix_hasher_add_bytes(
48 struct mtrix_hasher h, const void *vp, size_t n
49) {
50 for(const char *p = vp; n--;)
51 h = mtrix_hasher_add(h, *p++);
52 return h;
53}
54
55mtrix_hash mtrix_hash_str(const char *s) {
56 return mtrix_hasher_add_str(MTRIX_HASHER_INIT, s).h;
57}
58
59int mtrix_hash_cmp(const void *lhs_p, const void *rhs_p) {
60 const mtrix_hash lhs = *(const mtrix_hash*)lhs_p;
61 const mtrix_hash rhs = *(const mtrix_hash*)rhs_p;
62 return lhs < rhs ? -1 : rhs < lhs ? 1 : 0;
63}
64
65#endif
Wraps a value with methods to compute hashes of several types.
Definition hash.h:12
mtrix_hash h
Final hashed value.
Definition hash.h:14