hash_float_generic.hpp 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright 2005-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. // A general purpose hash function for non-zero floating point values.
  5. #if !defined(BOOST_FUNCTIONAL_HASH_DETAIL_HASH_FLOAT_GENERIC_HEADER)
  6. #define BOOST_FUNCTIONAL_HASH_DETAIL_HASH_FLOAT_GENERIC_HEADER
  7. #include <boost/functional/hash/detail/float_functions.hpp>
  8. #include <boost/integer/static_log2.hpp>
  9. #include <boost/functional/hash/detail/limits.hpp>
  10. #if defined(_MSC_VER) && (_MSC_VER >= 1020)
  11. # pragma once
  12. #endif
  13. #if defined(BOOST_MSVC)
  14. #pragma warning(push)
  15. #if BOOST_MSVC >= 1400
  16. #pragma warning(disable:6294) // Ill-defined for-loop: initial condition does
  17. // not satisfy test. Loop body not executed
  18. #endif
  19. #endif
  20. namespace boost
  21. {
  22. namespace hash_detail
  23. {
  24. inline void hash_float_combine(std::size_t& seed, std::size_t value)
  25. {
  26. seed ^= value + (seed<<6) + (seed>>2);
  27. }
  28. template <class T>
  29. inline std::size_t float_hash_impl2(T v)
  30. {
  31. boost::hash_detail::call_frexp<T> frexp;
  32. boost::hash_detail::call_ldexp<T> ldexp;
  33. int exp = 0;
  34. v = frexp(v, &exp);
  35. // A postive value is easier to hash, so combine the
  36. // sign with the exponent and use the absolute value.
  37. if(v < 0) {
  38. v = -v;
  39. exp += limits<T>::max_exponent -
  40. limits<T>::min_exponent;
  41. }
  42. // The result of frexp is always between 0.5 and 1, so its
  43. // top bit will always be 1. Subtract by 0.5 to remove that.
  44. v -= T(0.5);
  45. v = ldexp(v, limits<std::size_t>::digits + 1);
  46. std::size_t seed = static_cast<std::size_t>(v);
  47. v -= seed;
  48. // ceiling(digits(T) * log2(radix(T))/ digits(size_t)) - 1;
  49. std::size_t const length
  50. = (limits<T>::digits *
  51. boost::static_log2<limits<T>::radix>::value - 1)
  52. / limits<std::size_t>::digits;
  53. for(std::size_t i = 0; i != length; ++i)
  54. {
  55. v = ldexp(v, limits<std::size_t>::digits);
  56. std::size_t part = static_cast<std::size_t>(v);
  57. v -= part;
  58. hash_float_combine(seed, part);
  59. }
  60. hash_float_combine(seed, exp);
  61. return seed;
  62. }
  63. template <class T>
  64. inline std::size_t float_hash_impl(T v)
  65. {
  66. typedef BOOST_DEDUCED_TYPENAME select_hash_type<T>::type type;
  67. return float_hash_impl2(static_cast<type>(v));
  68. }
  69. }
  70. }
  71. #if defined(BOOST_MSVC)
  72. #pragma warning(pop)
  73. #endif
  74. #endif