reverse.hpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. //---------------------------------------------------------------------------//
  2. // Copyright (c) 2013 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_ALGORITHM_REVERSE_HPP
  11. #define BOOST_COMPUTE_ALGORITHM_REVERSE_HPP
  12. #include <boost/static_assert.hpp>
  13. #include <boost/compute/system.hpp>
  14. #include <boost/compute/command_queue.hpp>
  15. #include <boost/compute/detail/meta_kernel.hpp>
  16. #include <boost/compute/detail/iterator_range_size.hpp>
  17. #include <boost/compute/type_traits/is_device_iterator.hpp>
  18. namespace boost {
  19. namespace compute {
  20. namespace detail {
  21. template<class Iterator>
  22. struct reverse_kernel : public meta_kernel
  23. {
  24. reverse_kernel(Iterator first, Iterator last)
  25. : meta_kernel("reverse")
  26. {
  27. typedef typename std::iterator_traits<Iterator>::value_type value_type;
  28. // store size of the range
  29. m_size = detail::iterator_range_size(first, last);
  30. add_set_arg<const cl_uint>("size", static_cast<const cl_uint>(m_size));
  31. *this <<
  32. decl<cl_uint>("i") << " = get_global_id(0);\n" <<
  33. decl<cl_uint>("j") << " = size - get_global_id(0) - 1;\n" <<
  34. decl<value_type>("tmp") << "=" << first[var<cl_uint>("i")] << ";\n" <<
  35. first[var<cl_uint>("i")] << "=" << first[var<cl_uint>("j")] << ";\n" <<
  36. first[var<cl_uint>("j")] << "= tmp;\n";
  37. }
  38. void exec(command_queue &queue)
  39. {
  40. exec_1d(queue, 0, m_size / 2);
  41. }
  42. size_t m_size;
  43. };
  44. } // end detail namespace
  45. /// Reverses the elements in the range [\p first, \p last).
  46. ///
  47. /// Space complexity: \Omega(1)
  48. ///
  49. /// \see reverse_copy()
  50. template<class Iterator>
  51. inline void reverse(Iterator first,
  52. Iterator last,
  53. command_queue &queue = system::default_queue())
  54. {
  55. BOOST_STATIC_ASSERT(is_device_iterator<Iterator>::value);
  56. size_t count = detail::iterator_range_size(first, last);
  57. if(count < 2){
  58. return;
  59. }
  60. detail::reverse_kernel<Iterator> kernel(first, last);
  61. kernel.exec(queue);
  62. }
  63. } // end compute namespace
  64. } // end boost namespace
  65. #endif // BOOST_COMPUTE_ALGORITHM_REVERSE_HPP