replace.hpp 2.3 KB

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