You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.5 KiB

  1. /* The MIT License
  2. Copyright (C) 2012 Zilong Tan (eric.zltan@gmail.com)
  3. Permission is hereby granted, free of charge, to any person
  4. obtaining a copy of this software and associated documentation
  5. files (the "Software"), to deal in the Software without
  6. restriction, including without limitation the rights to use, copy,
  7. modify, merge, publish, distribute, sublicense, and/or sell copies
  8. of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be
  11. included in all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  13. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  14. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  15. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  16. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  17. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  18. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. SOFTWARE.
  20. */
  21. #include "fasthash.h"
  22. // Compression function for Merkle-Damgard construction.
  23. // This function is generated using the framework provided.
  24. #define mix(h) ({ \
  25. (h) ^= (h) >> 23; \
  26. (h) *= 0x2127599bf4325c37ULL; \
  27. (h) ^= (h) >> 47; })
  28. uint64_t
  29. fasthash64(const void *buf,
  30. size_t len,
  31. uint64_t seed)
  32. {
  33. const uint64_t m = 0x880355f21e6d1965ULL;
  34. const uint64_t *pos = (const uint64_t *)buf;
  35. const uint64_t *end = pos + (len / 8);
  36. const unsigned char *pos2;
  37. uint64_t h = seed ^ (len * m);
  38. uint64_t v;
  39. while (pos != end) {
  40. v = *pos++;
  41. h ^= mix(v);
  42. h *= m;
  43. }
  44. pos2 = (const unsigned char*)pos;
  45. v = 0;
  46. switch (len & 7) {
  47. case 7: v ^= (uint64_t)pos2[6] << 48;
  48. case 6: v ^= (uint64_t)pos2[5] << 40;
  49. case 5: v ^= (uint64_t)pos2[4] << 32;
  50. case 4: v ^= (uint64_t)pos2[3] << 24;
  51. case 3: v ^= (uint64_t)pos2[2] << 16;
  52. case 2: v ^= (uint64_t)pos2[1] << 8;
  53. case 1: v ^= (uint64_t)pos2[0];
  54. h ^= mix(v);
  55. h *= m;
  56. }
  57. return mix(h);
  58. }
  59. uint32_t
  60. fasthash32(const void *buf,
  61. size_t len,
  62. uint32_t seed)
  63. {
  64. // the following trick converts the 64-bit hashcode to Fermat
  65. // residue, which shall retain information from both the higher
  66. // and lower parts of hashcode.
  67. uint64_t h;
  68. h = fasthash64(buf, len, seed);
  69. return (h - (h >> 32));
  70. }