reverse.hpp 2.2 KB

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