da_fnv.c 1.8 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. static uint64_t FNV_64_INIT = UINT64_C(0xcbf29ce484222325);
  18. static uint64_t FNV_64_PRIME = UINT64_C(0x100000001b3);
  19. static uint32_t FNV_32_INIT = 2166136261UL;
  20. static uint32_t FNV_32_PRIME = 16777619;
  21. uint32_t
  22. hash_fnv1_64(const char *key, size_t key_length)
  23. {
  24. uint64_t hash = FNV_64_INIT;
  25. size_t x;
  26. for (x = 0; x < key_length; x++) {
  27. hash *= FNV_64_PRIME;
  28. hash ^= (uint64_t)key[x];
  29. }
  30. return (uint32_t)hash;
  31. }
  32. uint32_t
  33. hash_fnv1a_64(const char *key, size_t key_length)
  34. {
  35. uint32_t hash = (uint32_t) FNV_64_INIT;
  36. size_t x;
  37. for (x = 0; x < key_length; x++) {
  38. uint32_t val = (uint32_t)key[x];
  39. hash ^= val;
  40. hash *= (uint32_t) FNV_64_PRIME;
  41. }
  42. return hash;
  43. }
  44. uint32_t
  45. hash_fnv1_32(const char *key, size_t key_length)
  46. {
  47. uint32_t hash = FNV_32_INIT;
  48. size_t x;
  49. for (x = 0; x < key_length; x++) {
  50. uint32_t val = (uint32_t)key[x];
  51. hash *= FNV_32_PRIME;
  52. hash ^= val;
  53. }
  54. return hash;
  55. }
  56. uint32_t
  57. hash_fnv1a_32(const char *key, size_t key_length)
  58. {
  59. uint32_t hash = FNV_32_INIT;
  60. size_t x;
  61. for (x= 0; x < key_length; x++) {
  62. uint32_t val = (uint32_t)key[x];
  63. hash ^= val;
  64. hash *= FNV_32_PRIME;
  65. }
  66. return hash;
  67. }