fnv1.hpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2008-2009 Daniel James.
  2. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  3. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4. // This code is also released into the public domain.
  5. // Algorithm from: http://www.isthe.com/chongo/tech/comp/fnv/
  6. #include <string>
  7. namespace hash
  8. {
  9. template <std::size_t FnvPrime, std::size_t OffsetBasis>
  10. struct basic_fnv_1
  11. {
  12. std::size_t operator()(std::string const& text) const
  13. {
  14. std::size_t hash = OffsetBasis;
  15. for(std::string::const_iterator it = text.begin(), end = text.end();
  16. it != end; ++it)
  17. {
  18. hash *= FnvPrime;
  19. hash ^= *it;
  20. }
  21. return hash;
  22. }
  23. };
  24. template <std::size_t FnvPrime, std::size_t OffsetBasis>
  25. struct basic_fnv_1a
  26. {
  27. std::size_t operator()(std::string const& text) const
  28. {
  29. std::size_t hash = OffsetBasis;
  30. for(std::string::const_iterator it = text.begin(), end = text.end();
  31. it != end; ++it)
  32. {
  33. hash ^= *it;
  34. hash *= FnvPrime;
  35. }
  36. return hash;
  37. }
  38. };
  39. // For 32 bit machines:
  40. const std::size_t fnv_prime = 16777619u;
  41. const std::size_t fnv_offset_basis = 2166136261u;
  42. // For 64 bit machines:
  43. // const std::size_t fnv_prime = 1099511628211u;
  44. // const std::size_t fnv_offset_basis = 14695981039346656037u;
  45. // For 128 bit machines:
  46. // const std::size_t fnv_prime = 309485009821345068724781401u;
  47. // const std::size_t fnv_offset_basis =
  48. // 275519064689413815358837431229664493455u;
  49. // For 256 bit machines:
  50. // const std::size_t fnv_prime =
  51. // 374144419156711147060143317175368453031918731002211u;
  52. // const std::size_t fnv_offset_basis =
  53. // 100029257958052580907070968620625704837092796014241193945225284501741471925557u;
  54. typedef basic_fnv_1<fnv_prime, fnv_offset_basis> fnv_1;
  55. typedef basic_fnv_1a<fnv_prime, fnv_offset_basis> fnv_1a;
  56. }