1 | /* |
2 | Simple DirectMedia Layer |
3 | Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org> |
4 | |
5 | This software is provided 'as-is', without any express or implied |
6 | warranty. In no event will the authors be held liable for any damages |
7 | arising from the use of this software. |
8 | |
9 | Permission is granted to anyone to use this software for any purpose, |
10 | including commercial applications, and to alter it and redistribute it |
11 | freely, subject to the following restrictions: |
12 | |
13 | 1. The origin of this software must not be misrepresented; you must not |
14 | claim that you wrote the original software. If you use this software |
15 | in a product, an acknowledgment in the product documentation would be |
16 | appreciated but is not required. |
17 | 2. Altered source versions must be plainly marked as such, and must not be |
18 | misrepresented as being the original software. |
19 | 3. This notice may not be removed or altered from any source distribution. |
20 | */ |
21 | #include "SDL_internal.h" |
22 | |
23 | // Public domain murmur3 32-bit hash algorithm |
24 | // |
25 | // Adapted from: https://en.wikipedia.org/wiki/MurmurHash |
26 | |
27 | static SDL_INLINE Uint32 murmur_32_scramble(Uint32 k) |
28 | { |
29 | k *= 0xcc9e2d51; |
30 | k = (k << 15) | (k >> 17); |
31 | k *= 0x1b873593; |
32 | return k; |
33 | } |
34 | |
35 | Uint32 SDLCALL SDL_murmur3_32(const void *data, size_t len, Uint32 seed) |
36 | { |
37 | const Uint8 *bytes = (const Uint8 *)data; |
38 | Uint32 hash = seed; |
39 | Uint32 k; |
40 | |
41 | // Read in groups of 4. |
42 | if ((((uintptr_t)bytes) & 3) == 0) { |
43 | // We can do aligned 32-bit reads |
44 | for (size_t i = len >> 2; i--; ) { |
45 | k = *(const Uint32 *)bytes; |
46 | k = SDL_Swap32LE(k); |
47 | bytes += sizeof(Uint32); |
48 | hash ^= murmur_32_scramble(k); |
49 | hash = (hash << 13) | (hash >> 19); |
50 | hash = hash * 5 + 0xe6546b64; |
51 | } |
52 | } else { |
53 | for (size_t i = len >> 2; i--; ) { |
54 | SDL_memcpy(&k, bytes, sizeof(Uint32)); |
55 | k = SDL_Swap32LE(k); |
56 | bytes += sizeof(Uint32); |
57 | hash ^= murmur_32_scramble(k); |
58 | hash = (hash << 13) | (hash >> 19); |
59 | hash = hash * 5 + 0xe6546b64; |
60 | } |
61 | } |
62 | |
63 | // Read the rest. |
64 | size_t left = (len & 3); |
65 | if (left) { |
66 | k = 0; |
67 | for (size_t i = left; i--; ) { |
68 | k <<= 8; |
69 | k |= bytes[i]; |
70 | } |
71 | |
72 | // A swap is *not* necessary here because the preceding loop already |
73 | // places the low bytes in the low places according to whatever endianness |
74 | // we use. Swaps only apply when the memory is copied in a chunk. |
75 | hash ^= murmur_32_scramble(k); |
76 | } |
77 | |
78 | /* Finalize. */ |
79 | hash ^= len; |
80 | hash ^= hash >> 16; |
81 | hash *= 0x85ebca6b; |
82 | hash ^= hash >> 13; |
83 | hash *= 0xc2b2ae35; |
84 | hash ^= hash >> 16; |
85 | |
86 | return hash; |
87 | } |
88 | |