aboutsummaryrefslogtreecommitdiff
path: root/include
diff options
context:
space:
mode:
Diffstat (limited to 'include')
-rw-r--r--include/hash.h94
1 files changed, 94 insertions, 0 deletions
diff --git a/include/hash.h b/include/hash.h
new file mode 100644
index 0000000..4c26b46
--- /dev/null
+++ b/include/hash.h
@@ -0,0 +1,94 @@
1// hash.h --- hashing functions -*- C -*-
2//
3// Copyright (c) 2026 Martin Michalec <martin@michalec.dev>
4//
5// SPDX-License-Identifier: MIT
6//
7// This file is part of COSMOS Codebase.
8//
9// Commentary:
10//
11// Code:
12
13#ifndef INCLUDED_COSMOS_HASH_H
14#define INCLUDED_COSMOS_HASH_H
15
16#include "types.h"
17
18#ifndef HASH_NO_FEAT_CRC_32
19
20#define HASH_CRC_32_INIT 0xffffffff
21
22u32 hash_crc_32_update (u32 crc, const void *buf, usz len);
23
24static inline u32
25hash_crc_32_final (u32 crc)
26{
27 return crc ^ 0xffffffff;
28}
29
30static inline u32
31hash_crc_32 (const void *buf, usz len)
32{
33 return hash_crc_32_final (hash_crc_32_update (HASH_CRC_32_INIT, buf, len));
34}
35
36#endif // HASH_NO_FEAT_CRC_32
37
38#ifndef HASH_NO_FEAT_FNV1A_32
39
40#define HASH_FNV1A_32_INIT 0x811c9dc5
41#define HASH_FNV1A_32_PRIME 0x01000193
42
43static inline u32
44hash_fnv1a_32_update (u32 hash, const void *buf, usz sz)
45{
46 const u8 *ptr = buf;
47 const u8 *end = ptr + sz;
48
49 for (; ptr < end; ptr++) {
50 hash ^= *ptr;
51 hash *= HASH_FNV1A_32_PRIME;
52 }
53
54 return hash;
55}
56
57static inline u32
58hash_fnv1a_32 (const void *buf, usz sz)
59{
60 return hash_fnv1a_32_update (HASH_FNV1A_32_INIT, buf, sz);
61}
62
63#endif // HASH_NO_FEAT_FNV1A_32
64
65#ifndef HASH_NO_FEAT_FNV1A_64
66
67#define HASH_FNV1A_64_INIT 0xcbf29ce484222325
68#define HASH_FNV1A_64_PRIME 0x00000100000001b3
69
70static inline u64
71hash_fnv1a_64_update (u64 h, const void *buf, usz sz)
72{
73 const u8 *p = (const u8 *) buf;
74 const u8 *end = p + sz;
75
76 while (p < end) {
77 h ^= *p++;
78 h *= HASH_FNV1A_64_PRIME;
79 }
80
81 return h;
82}
83
84static inline u64
85hash_fnv1a_64 (const void *buf, usz sz)
86{
87 return hash_fnv1a_64_update (HASH_FNV1A_64_INIT, buf, sz);
88}
89
90#endif // HASH_NO_FEAT_FNV1A_64
91
92#endif // INCLUDED_COSMOS_HASH_H
93
94// hash.h ends here