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_H
11#define _LIBCPP___ALGORITHM_FOR_EACH_H
12
13#include <__algorithm/for_each_segment.h>
14#include <__algorithm/specialized_algorithms.h>
15#include <__config>
16#include <__functional/identity.h>
17#include <__iterator/segmented_iterator.h>
18#include <__type_traits/invoke.h>
19#include <__type_traits/is_same.h>
20
21#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
22# pragma GCC system_header
23#endif
24
25_LIBCPP_BEGIN_NAMESPACE_STD
26
27template <class _InputIterator, class _Sent, class _Func, class _Proj>
28_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 _InputIterator
29__for_each(_InputIterator __first, _Sent __last, _Func& __func, _Proj& __proj) {
30#ifndef _LIBCPP_CXX03_LANG
31 if constexpr (using _SpecialAlg =
32 __specialized_algorithm<_Algorithm::__for_each, __iterator_pair<_InputIterator, _Sent>>;
33 _SpecialAlg::__has_algorithm) {
34 _SpecialAlg()(__first, __last, __func, __proj);
35 return __last;
36 } else if constexpr (is_same<_InputIterator, _Sent>::value && __is_segmented_iterator_v<_InputIterator>) {
37 using __local_iterator_t = typename __segmented_iterator_traits<_InputIterator>::__local_iterator;
38 std::__for_each_segment(__first, __last, [&](__local_iterator_t __lfirst, __local_iterator_t __llast) {
39 std::__for_each(__lfirst, __llast, __func, __proj);
40 });
41 return __last;
42 }
43#endif
44 for (; __first != __last; ++__first)
45 std::__invoke(__func, std::__invoke(__proj, *__first));
46 return __first;
47}
48
49template <class _InputIterator, class _Func>
50_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 _Func
51for_each(_InputIterator __first, _InputIterator __last, _Func __f) {
52 __identity __proj;
53 std::__for_each(__first, __last, __f, __proj);
54 return __f;
55}
56
57_LIBCPP_END_NAMESPACE_STD
58
59#endif // _LIBCPP___ALGORITHM_FOR_EACH_H
60