replace.hpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. //---------------------------------------------------------------------------//
  2. // Copyright (c) 2013 Kyle Lutz <[email protected]>
  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_REPLACE_HPP
  11. #define BOOST_COMPUTE_ALGORITHM_REPLACE_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, class T>
  22. class replace_kernel : public meta_kernel
  23. {
  24. public:
  25. replace_kernel()
  26. : meta_kernel("replace")
  27. {
  28. m_count = 0;
  29. }
  30. void set_range(Iterator first, Iterator last)
  31. {
  32. m_count = detail::iterator_range_size(first, last);
  33. *this <<
  34. "const uint i = get_global_id(0);\n" <<
  35. "if(" << first[var<cl_uint>("i")] << " == " << var<T>("old_value") << ")\n" <<
  36. " " << first[var<cl_uint>("i")] << '=' << var<T>("new_value") << ";\n";
  37. }
  38. void set_old_value(const T &old_value)
  39. {
  40. add_set_arg<T>("old_value", old_value);
  41. }
  42. void set_new_value(const T &new_value)
  43. {
  44. add_set_arg<T>("new_value", new_value);
  45. }
  46. void exec(command_queue &queue)
  47. {
  48. if(m_count == 0){
  49. // nothing to do
  50. return;
  51. }
  52. exec_1d(queue, 0, m_count);
  53. }
  54. private:
  55. size_t m_count;
  56. };
  57. } // end detail namespace
  58. /// Replaces each instance of \p old_value in the range [\p first,
  59. /// \p last) with \p new_value.
  60. ///
  61. /// Space complexity: \Omega(1)
  62. template<class Iterator, class T>
  63. inline void replace(Iterator first,
  64. Iterator last,
  65. const T &old_value,
  66. const T &new_value,
  67. command_queue &queue = system::default_queue())
  68. {
  69. BOOST_STATIC_ASSERT(is_device_iterator<Iterator>::value);
  70. detail::replace_kernel<Iterator, T> kernel;
  71. kernel.set_range(first, last);
  72. kernel.set_old_value(old_value);
  73. kernel.set_new_value(new_value);
  74. kernel.exec(queue);
  75. }
  76. } // end compute namespace
  77. } // end boost namespace
  78. #endif // BOOST_COMPUTE_ALGORITHM_REPLACE_HPP