search.hpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. //---------------------------------------------------------------------------//
  2. // Copyright (c) 2014 Roshan <thisisroshansmail@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_SEARCH_HPP
  11. #define BOOST_COMPUTE_ALGORITHM_SEARCH_HPP
  12. #include <boost/compute/algorithm/detail/search_all.hpp>
  13. #include <boost/compute/algorithm/find.hpp>
  14. #include <boost/compute/container/vector.hpp>
  15. #include <boost/compute/detail/iterator_range_size.hpp>
  16. #include <boost/compute/detail/meta_kernel.hpp>
  17. #include <boost/compute/system.hpp>
  18. namespace boost {
  19. namespace compute {
  20. ///
  21. /// \brief Substring matching algorithm
  22. ///
  23. /// Searches for the first match of the pattern [p_first, p_last)
  24. /// in text [t_first, t_last).
  25. /// \return Iterator pointing to beginning of first occurrence
  26. ///
  27. /// \param t_first Iterator pointing to start of text
  28. /// \param t_last Iterator pointing to end of text
  29. /// \param p_first Iterator pointing to start of pattern
  30. /// \param p_last Iterator pointing to end of pattern
  31. /// \param queue Queue on which to execute
  32. ///
  33. template<class TextIterator, class PatternIterator>
  34. inline TextIterator search(TextIterator t_first,
  35. TextIterator t_last,
  36. PatternIterator p_first,
  37. PatternIterator p_last,
  38. command_queue &queue = system::default_queue())
  39. {
  40. // there is no need to check if pattern starts at last n - 1 indices
  41. vector<uint_> matching_indices(
  42. detail::iterator_range_size(t_first, t_last)
  43. - detail::iterator_range_size(p_first, p_last) + 1,
  44. queue.get_context()
  45. );
  46. // search_kernel puts value 1 at every index in vector where pattern starts at
  47. detail::search_kernel<PatternIterator,
  48. TextIterator,
  49. vector<uint_>::iterator> kernel;
  50. kernel.set_range(p_first, p_last, t_first, t_last, matching_indices.begin());
  51. kernel.exec(queue);
  52. vector<uint_>::iterator index = ::boost::compute::find(
  53. matching_indices.begin(), matching_indices.end(), uint_(1), queue
  54. );
  55. // pattern was not found
  56. if(index == matching_indices.end())
  57. return t_last;
  58. return t_first + detail::iterator_range_size(matching_indices.begin(), index);
  59. }
  60. } //end compute namespace
  61. } //end boost namespace
  62. #endif // BOOST_COMPUTE_ALGORITHM_SEARCH_HPP