da_hsieh.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. #undef get16bits
  18. #if (defined(__GNUC__) && defined(__i386__))
  19. #define get16bits(d) (*((const uint16_t *) (d)))
  20. #endif
  21. #if !defined (get16bits)
  22. #define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\
  23. +(uint32_t)(((const uint8_t *)(d))[0]) )
  24. #endif
  25. uint32_t
  26. hash_hsieh(const char *key, size_t key_length)
  27. {
  28. uint32_t hash = 0, tmp;
  29. int rem;
  30. if (key_length <= 0 || key == NULL) {
  31. return 0;
  32. }
  33. rem = key_length & 3;
  34. key_length >>= 2;
  35. /* Main loop */
  36. for (;key_length > 0; key_length--) {
  37. hash += get16bits (key);
  38. tmp = (get16bits (key+2) << 11) ^ hash;
  39. hash = (hash << 16) ^ tmp;
  40. key += 2*sizeof (uint16_t);
  41. hash += hash >> 11;
  42. }
  43. /* Handle end cases */
  44. switch (rem) {
  45. case 3:
  46. hash += get16bits (key);
  47. hash ^= hash << 16;
  48. hash ^= (uint32_t)key[sizeof (uint16_t)] << 18;
  49. hash += hash >> 11;
  50. break;
  51. case 2:
  52. hash += get16bits (key);
  53. hash ^= hash << 11;
  54. hash += hash >> 17;
  55. break;
  56. case 1:
  57. hash += (unsigned char)(*key);
  58. hash ^= hash << 10;
  59. hash += hash >> 1;
  60. default:
  61. break;
  62. }
  63. /* Force "avalanching" of final 127 bits */
  64. hash ^= hash << 3;
  65. hash += hash >> 5;
  66. hash ^= hash << 4;
  67. hash += hash >> 17;
  68. hash ^= hash << 25;
  69. hash += hash >> 6;
  70. return hash;
  71. }