prev.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. #ifndef _LIBCPP___ITERATOR_PREV_H
  10. #define _LIBCPP___ITERATOR_PREV_H
  11. #include <__assert>
  12. #include <__config>
  13. #include <__iterator/advance.h>
  14. #include <__iterator/concepts.h>
  15. #include <__iterator/incrementable_traits.h>
  16. #include <__iterator/iterator_traits.h>
  17. #include <__type_traits/enable_if.h>
  18. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  19. # pragma GCC system_header
  20. #endif
  21. _LIBCPP_BEGIN_NAMESPACE_STD
  22. template <class _InputIter, __enable_if_t<__has_input_iterator_category<_InputIter>::value, int> = 0>
  23. inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_SINCE_CXX17
  24. _InputIter
  25. prev(_InputIter __x, typename iterator_traits<_InputIter>::difference_type __n = 1) {
  26. _LIBCPP_ASSERT_UNCATEGORIZED(__n <= 0 || __has_bidirectional_iterator_category<_InputIter>::value,
  27. "Attempt to prev(it, n) with a positive n on a non-bidirectional iterator");
  28. _VSTD::advance(__x, -__n);
  29. return __x;
  30. }
  31. #if _LIBCPP_STD_VER >= 20
  32. // [range.iter.op.prev]
  33. namespace ranges {
  34. namespace __prev {
  35. struct __fn {
  36. template <bidirectional_iterator _Ip>
  37. _LIBCPP_HIDE_FROM_ABI
  38. constexpr _Ip operator()(_Ip __x) const {
  39. --__x;
  40. return __x;
  41. }
  42. template <bidirectional_iterator _Ip>
  43. _LIBCPP_HIDE_FROM_ABI
  44. constexpr _Ip operator()(_Ip __x, iter_difference_t<_Ip> __n) const {
  45. ranges::advance(__x, -__n);
  46. return __x;
  47. }
  48. template <bidirectional_iterator _Ip>
  49. _LIBCPP_HIDE_FROM_ABI constexpr _Ip operator()(_Ip __x, iter_difference_t<_Ip> __n, _Ip ___bound_iter) const {
  50. ranges::advance(__x, -__n, ___bound_iter);
  51. return __x;
  52. }
  53. };
  54. } // namespace __prev
  55. inline namespace __cpo {
  56. inline constexpr auto prev = __prev::__fn{};
  57. } // namespace __cpo
  58. } // namespace ranges
  59. #endif // _LIBCPP_STD_VER >= 20
  60. _LIBCPP_END_NAMESPACE_STD
  61. #endif // _LIBCPP___ITERATOR_PREV_H