SDL_murmur3.c 2.7 KB

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