da_chash.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. #define mix(a,b,c) \
  18. { \
  19. a=a-b; a=a-c; a=a^(c>>13); \
  20. b=b-c; b=b-a; b=b^(a<<8); \
  21. c=c-a; c=c-b; c=c^(b>>13); \
  22. a=a-b; a=a-c; a=a^(c>>12); \
  23. b=b-c; b=b-a; b=b^(a<<16); \
  24. c=c-a; c=c-b; c=c^(b>>5); \
  25. a=a-b; a=a-c; a=a^(c>>3); \
  26. b=b-c; b=b-a; b=b^(a<<10); \
  27. c=c-a; c=c-b; c=c^(b>>15); \
  28. }
  29. typedef uint32_t u4;
  30. uint32_t hash_chash(const char *k, size_t length)
  31. {
  32. uint32_t a,b,c; /* the internal state */
  33. u4 len; /* how many key bytes still need mixing */
  34. /* Set up the internal state */
  35. len = length;
  36. a = b = 0x9e3779b9; /* the golden ratio; an arbitrary value */
  37. // 'TMJR'
  38. c = 0x544D4A52; /* variable initialization of internal state */
  39. /*---------------------------------------- handle most of the key */
  40. while (len >= 12)
  41. {
  42. a=a+(k[0]+((u4)k[1]<<8)+((u4)k[2]<<16) +((u4)k[3]<<24));
  43. b=b+(k[4]+((u4)k[5]<<8)+((u4)k[6]<<16) +((u4)k[7]<<24));
  44. c=c+(k[8]+((u4)k[9]<<8)+((u4)k[10]<<16)+((u4)k[11]<<24));
  45. mix(a,b,c);
  46. k = k+12; len = len-12;
  47. }
  48. /*------------------------------------- handle the last 11 bytes */
  49. c = c+length;
  50. switch(len) /* all the case statements fall through */
  51. {
  52. case 11: c=c+((u4)k[10]<<24);
  53. case 10: c=c+((u4)k[9]<<16);
  54. case 9 : c=c+((u4)k[8]<<8);
  55. /* the first byte of c is reserved for the length */
  56. case 8 : b=b+((u4)k[7]<<24);
  57. case 7 : b=b+((u4)k[6]<<16);
  58. case 6 : b=b+((u4)k[5]<<8);
  59. case 5 : b=b+k[4];
  60. case 4 : a=a+((u4)k[3]<<24);
  61. case 3 : a=a+((u4)k[2]<<16);
  62. case 2 : a=a+((u4)k[1]<<8);
  63. case 1 : a=a+k[0];
  64. /* case 0: nothing left to add */
  65. }
  66. mix(a,b,c);
  67. /*-------------------------------------------- report the result */
  68. return c;
  69. }