fasthash.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. static inline uint64_t mix(uint64_t h) {
  25. h ^= h >> 23;
  26. h *= 0x2127599bf4325c37ULL;
  27. h ^= h >> 47;
  28. return h;
  29. }
  30. uint64_t fasthash64(const void *buf, size_t len, uint64_t seed)
  31. {
  32. const uint64_t m = 0x880355f21e6d1965ULL;
  33. const uint64_t *pos = (const uint64_t *)buf;
  34. const uint64_t *end = pos + (len / 8);
  35. const unsigned char *pos2;
  36. uint64_t h = seed ^ (len * m);
  37. uint64_t v;
  38. while (pos != end) {
  39. v = *pos++;
  40. h ^= mix(v);
  41. h *= m;
  42. }
  43. pos2 = (const unsigned char*)pos;
  44. v = 0;
  45. switch (len & 7) {
  46. case 7: v ^= (uint64_t)pos2[6] << 48;
  47. case 6: v ^= (uint64_t)pos2[5] << 40;
  48. case 5: v ^= (uint64_t)pos2[4] << 32;
  49. case 4: v ^= (uint64_t)pos2[3] << 24;
  50. case 3: v ^= (uint64_t)pos2[2] << 16;
  51. case 2: v ^= (uint64_t)pos2[1] << 8;
  52. case 1: v ^= (uint64_t)pos2[0];
  53. h ^= mix(v);
  54. h *= m;
  55. }
  56. return mix(h);
  57. }
  58. uint32_t fasthash32(const void *buf, size_t len, uint32_t seed)
  59. {
  60. // the following trick converts the 64-bit hashcode to Fermat
  61. // residue, which shall retain information from both the higher
  62. // and lower parts of hashcode.
  63. uint64_t h = fasthash64(buf, len, seed);
  64. return h - (h >> 32);
  65. }