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___ITERATOR_PREV_H
11 #define _LIBCPP___ITERATOR_PREV_H
12 
13 #include <__assert>
14 #include <__config>
15 #include <__iterator/advance.h>
16 #include <__iterator/concepts.h>
17 #include <__iterator/incrementable_traits.h>
18 #include <__iterator/iterator_traits.h>
19 #include <__type_traits/enable_if.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 
27 template <class _InputIter, __enable_if_t<__has_input_iterator_category<_InputIter>::value, int> = 0>
28 inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX17 _InputIter
29 prev(_InputIter __x, typename iterator_traits<_InputIter>::difference_type __n = 1) {
30   _LIBCPP_ASSERT_UNCATEGORIZED(__n <= 0 || __has_bidirectional_iterator_category<_InputIter>::value,
31                                "Attempt to prev(it, n) with a positive n on a non-bidirectional iterator");
32   std::advance(__x, -__n);
33   return __x;
34 }
35 
36 #if _LIBCPP_STD_VER >= 20
37 
38 // [range.iter.op.prev]
39 
40 namespace ranges {
41 namespace __prev {
42 
43 struct __fn {
44   template <bidirectional_iterator _Ip>
45   _LIBCPP_HIDE_FROM_ABI constexpr _Ip operator()(_Ip __x) const {
46     --__x;
47     return __x;
48   }
49 
50   template <bidirectional_iterator _Ip>
51   _LIBCPP_HIDE_FROM_ABI constexpr _Ip operator()(_Ip __x, iter_difference_t<_Ip> __n) const {
52     ranges::advance(__x, -__n);
53     return __x;
54   }
55 
56   template <bidirectional_iterator _Ip>
57   _LIBCPP_HIDE_FROM_ABI constexpr _Ip operator()(_Ip __x, iter_difference_t<_Ip> __n, _Ip __bound_iter) const {
58     ranges::advance(__x, -__n, __bound_iter);
59     return __x;
60   }
61 };
62 
63 } // namespace __prev
64 
65 inline namespace __cpo {
66 inline constexpr auto prev = __prev::__fn{};
67 } // namespace __cpo
68 } // namespace ranges
69 
70 #endif // _LIBCPP_STD_VER >= 20
71 
72 _LIBCPP_END_NAMESPACE_STD
73 
74 #endif // _LIBCPP___ITERATOR_PREV_H
75