da_murmur.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * Copyright [2021] JD.com, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "da_hashkit.h"
  17. uint32_t
  18. hash_murmur(const char *key, size_t length)
  19. {
  20. /*
  21. * 'm' and 'r' are mixing constants generated offline. They're not
  22. * really 'magic', they just happen to work well.
  23. */
  24. const unsigned int m = 0x5bd1e995;
  25. const uint32_t seed = (0xdeadbeef * (uint32_t)length);
  26. const int r = 24;
  27. /* Initialize the hash to a 'random' value */
  28. uint32_t h = seed ^ (uint32_t)length;
  29. /* Mix 4 bytes at a time into the hash */
  30. const unsigned char * data = (const unsigned char *)key;
  31. while (length >= 4) {
  32. unsigned int k = *(unsigned int *)data;
  33. k *= m;
  34. k ^= k >> r;
  35. k *= m;
  36. h *= m;
  37. h ^= k;
  38. data += 4;
  39. length -= 4;
  40. }
  41. /* Handle the last few bytes of the input array */
  42. switch(length) {
  43. case 3:
  44. h ^= ((uint32_t)data[2]) << 16;
  45. case 2:
  46. h ^= ((uint32_t)data[1]) << 8;
  47. case 1:
  48. h ^= data[0];
  49. h *= m;
  50. default:
  51. break;
  52. };
  53. /*
  54. * Do a few final mixes of the hash to ensure the last few bytes are
  55. * well-incorporated.
  56. */
  57. h ^= h >> 13;
  58. h *= m;
  59. h ^= h >> 15;
  60. return h;
  61. }