hash.hpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. //---------------------------------------------------------------------------//
  2. // Copyright (c) 2013-2014 Kyle Lutz <kyle.r.lutz@gmail.com>
  3. //
  4. // Distributed under the Boost Software License, Version 1.0
  5. // See accompanying file LICENSE_1_0.txt or copy at
  6. // http://www.boost.org/LICENSE_1_0.txt
  7. //
  8. // See http://boostorg.github.com/compute for more information.
  9. //---------------------------------------------------------------------------//
  10. #ifndef BOOST_COMPUTE_FUNCTIONAL_HASH_HPP
  11. #define BOOST_COMPUTE_FUNCTIONAL_HASH_HPP
  12. #include <boost/compute/function.hpp>
  13. #include <boost/compute/types/fundamental.hpp>
  14. namespace boost {
  15. namespace compute {
  16. namespace detail {
  17. template<class Key>
  18. std::string make_hash_function_name()
  19. {
  20. return std::string("boost_hash_") + type_name<Key>();
  21. }
  22. template<class Key>
  23. inline std::string make_hash_function_source()
  24. {
  25. std::stringstream source;
  26. source << "inline ulong " << make_hash_function_name<Key>()
  27. << "(const " << type_name<Key>() << " x)\n"
  28. << "{\n"
  29. // note we reinterpret the argument as a 32-bit uint and
  30. // then promote it to a 64-bit ulong for the result type
  31. << " ulong a = as_uint(x);\n"
  32. << " a = (a ^ 61) ^ (a >> 16);\n"
  33. << " a = a + (a << 3);\n"
  34. << " a = a ^ (a >> 4);\n"
  35. << " a = a * 0x27d4eb2d;\n"
  36. << " a = a ^ (a >> 15);\n"
  37. << " return a;\n"
  38. << "}\n";
  39. return source.str();
  40. }
  41. template<class Key>
  42. struct hash_impl
  43. {
  44. typedef Key argument_type;
  45. typedef ulong_ result_type;
  46. hash_impl()
  47. : m_function("")
  48. {
  49. m_function = make_function_from_source<result_type(argument_type)>(
  50. make_hash_function_name<argument_type>(),
  51. make_hash_function_source<argument_type>()
  52. );
  53. }
  54. template<class Arg>
  55. invoked_function<result_type, boost::tuple<Arg> >
  56. operator()(const Arg &arg) const
  57. {
  58. return m_function(arg);
  59. }
  60. function<result_type(argument_type)> m_function;
  61. };
  62. } // end detail namespace
  63. /// The hash function returns a hash value for the input value.
  64. ///
  65. /// The return type is \c ulong_ (the OpenCL unsigned long type).
  66. template<class Key> struct hash;
  67. /// \internal_
  68. template<> struct hash<int_> : detail::hash_impl<int_> { };
  69. /// \internal_
  70. template<> struct hash<uint_> : detail::hash_impl<uint_> { };
  71. /// \internal_
  72. template<> struct hash<float_> : detail::hash_impl<float_> { };
  73. } // end compute namespace
  74. } // end boost namespace
  75. #endif // BOOST_COMPUTE_FUNCTIONAL_HASH_HPP