| 1 | // -*- C++ -*- |
| 2 | //===----------------------------------------------------------------------===// |
| 3 | // |
| 4 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 5 | // See https://llvm.org/LICENSE.txt for license information. |
| 6 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | |
| 10 | #ifndef _LIBCPP___ALGORITHM_FOR_EACH_N_H |
| 11 | #define _LIBCPP___ALGORITHM_FOR_EACH_N_H |
| 12 | |
| 13 | #include <__algorithm/for_each.h> |
| 14 | #include <__algorithm/for_each_n_segment.h> |
| 15 | #include <__config> |
| 16 | #include <__functional/identity.h> |
| 17 | #include <__iterator/iterator_traits.h> |
| 18 | #include <__iterator/segmented_iterator.h> |
| 19 | #include <__type_traits/invoke.h> |
| 20 | #include <__utility/convert_to_integral.h> |
| 21 | #include <__utility/move.h> |
| 22 | |
| 23 | #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) |
| 24 | # pragma GCC system_header |
| 25 | #endif |
| 26 | |
| 27 | _LIBCPP_PUSH_MACROS |
| 28 | #include <__undef_macros> |
| 29 | |
| 30 | _LIBCPP_BEGIN_NAMESPACE_STD |
| 31 | |
| 32 | template <class _InputIterator, class _Size, class _Func, class _Proj> |
| 33 | _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 _InputIterator |
| 34 | __for_each_n(_InputIterator __first, _Size __orig_n, _Func& __f, _Proj& __proj) { |
| 35 | typedef decltype(std::__convert_to_integral(__orig_n)) _IntegralSize; |
| 36 | _IntegralSize __n = __orig_n; |
| 37 | |
| 38 | #ifndef _LIBCPP_CXX03_LANG |
| 39 | if constexpr (__is_segmented_iterator_v<_InputIterator>) { |
| 40 | using __local_iterator = typename __segmented_iterator_traits<_InputIterator>::__local_iterator; |
| 41 | if constexpr (__has_random_access_iterator_category<__local_iterator>::value) { |
| 42 | return std::__for_each_n_segment(__first, __orig_n, [&](__local_iterator __lfirst, __local_iterator __llast) { |
| 43 | std::__for_each(__lfirst, __llast, __f, __proj); |
| 44 | }); |
| 45 | } else { |
| 46 | return std::__for_each(__first, __first + __n, __f, __proj); |
| 47 | } |
| 48 | } else |
| 49 | #endif |
| 50 | { |
| 51 | while (__n > 0) { |
| 52 | std::__invoke(__f, std::__invoke(__proj, *__first)); |
| 53 | ++__first; |
| 54 | --__n; |
| 55 | } |
| 56 | return std::move(__first); |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | #if _LIBCPP_STD_VER >= 17 |
| 61 | |
| 62 | template <class _InputIterator, class _Size, class _Func> |
| 63 | inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 _InputIterator |
| 64 | for_each_n(_InputIterator __first, _Size __orig_n, _Func __f) { |
| 65 | __identity __proj; |
| 66 | return std::__for_each_n(__first, __orig_n, __f, __proj); |
| 67 | } |
| 68 | |
| 69 | #endif // _LIBCPP_STD_VER >= 17 |
| 70 | |
| 71 | _LIBCPP_END_NAMESPACE_STD |
| 72 | |
| 73 | _LIBCPP_POP_MACROS |
| 74 | |
| 75 | #endif // _LIBCPP___ALGORITHM_FOR_EACH_N_H |