span.hpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*!
  2. @file
  3. Defines `boost::hana::span`.
  4. @copyright Louis Dionne 2013-2017
  5. Distributed under the Boost Software License, Version 1.0.
  6. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
  7. */
  8. #ifndef BOOST_HANA_SPAN_HPP
  9. #define BOOST_HANA_SPAN_HPP
  10. #include <boost/hana/fwd/span.hpp>
  11. #include <boost/hana/at.hpp>
  12. #include <boost/hana/concept/sequence.hpp>
  13. #include <boost/hana/config.hpp>
  14. #include <boost/hana/core/dispatch.hpp>
  15. #include <boost/hana/core/make.hpp>
  16. #include <boost/hana/detail/nested_by.hpp> // required by fwd decl
  17. #include <boost/hana/detail/first_unsatisfied_index.hpp>
  18. #include <boost/hana/length.hpp>
  19. #include <boost/hana/pair.hpp>
  20. #include <boost/hana/unpack.hpp>
  21. #include <cstddef>
  22. #include <utility>
  23. BOOST_HANA_NAMESPACE_BEGIN
  24. //! @cond
  25. template <typename Xs, typename Pred>
  26. constexpr auto span_t::operator()(Xs&& xs, Pred&& pred) const {
  27. using S = typename hana::tag_of<Xs>::type;
  28. using Span = BOOST_HANA_DISPATCH_IF(span_impl<S>,
  29. hana::Sequence<S>::value
  30. );
  31. #ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS
  32. static_assert(hana::Sequence<S>::value,
  33. "hana::span(xs, pred) requires 'xs' to be a Sequence");
  34. #endif
  35. return Span::apply(static_cast<Xs&&>(xs), static_cast<Pred&&>(pred));
  36. }
  37. //! @endcond
  38. template <typename S, bool condition>
  39. struct span_impl<S, when<condition>> : default_ {
  40. template <typename Xs, std::size_t ...before, std::size_t ...after>
  41. static constexpr auto span_helper(Xs&& xs, std::index_sequence<before...>,
  42. std::index_sequence<after...>)
  43. {
  44. return hana::make_pair(
  45. hana::make<S>(hana::at_c<before>(static_cast<Xs&&>(xs))...),
  46. hana::make<S>(hana::at_c<sizeof...(before) + after>(static_cast<Xs&&>(xs))...)
  47. );
  48. }
  49. template <typename Xs, typename Pred>
  50. static constexpr auto apply(Xs&& xs, Pred&&) {
  51. using FirstUnsatisfied = decltype(
  52. hana::unpack(static_cast<Xs&&>(xs),
  53. detail::first_unsatisfied_index<Pred&&>{})
  54. );
  55. constexpr std::size_t breakpoint = FirstUnsatisfied::value;
  56. constexpr std::size_t N = decltype(hana::length(xs))::value;
  57. return span_helper(static_cast<Xs&&>(xs),
  58. std::make_index_sequence<breakpoint>{},
  59. std::make_index_sequence<N - breakpoint>{});
  60. }
  61. };
  62. BOOST_HANA_NAMESPACE_END
  63. #endif // !BOOST_HANA_SPAN_HPP