prev.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX17 _InputIter
  24. prev(_InputIter __x, typename iterator_traits<_InputIter>::difference_type __n = 1) {
  25. // Calling `advance` with a negative value on a non-bidirectional iterator is a no-op in the current implementation.
  26. // Note that this check duplicates the similar check in `std::advance`.
  27. _LIBCPP_ASSERT_PEDANTIC(__n <= 0 || __has_bidirectional_iterator_category<_InputIter>::value,
  28. "Attempt to prev(it, n) with a positive n on a non-bidirectional iterator");
  29. std::advance(__x, -__n);
  30. return __x;
  31. }
  32. #if _LIBCPP_STD_VER >= 20
  33. // [range.iter.op.prev]
  34. namespace ranges {
  35. namespace __prev {
  36. struct __fn {
  37. template <bidirectional_iterator _Ip>
  38. _LIBCPP_HIDE_FROM_ABI constexpr _Ip operator()(_Ip __x) const {
  39. --__x;
  40. return __x;
  41. }
  42. template <bidirectional_iterator _Ip>
  43. _LIBCPP_HIDE_FROM_ABI constexpr _Ip operator()(_Ip __x, iter_difference_t<_Ip> __n) const {
  44. ranges::advance(__x, -__n);
  45. return __x;
  46. }
  47. template <bidirectional_iterator _Ip>
  48. _LIBCPP_HIDE_FROM_ABI constexpr _Ip operator()(_Ip __x, iter_difference_t<_Ip> __n, _Ip ___bound_iter) const {
  49. ranges::advance(__x, -__n, ___bound_iter);
  50. return __x;
  51. }
  52. };
  53. } // namespace __prev
  54. inline namespace __cpo {
  55. inline constexpr auto prev = __prev::__fn{};
  56. } // namespace __cpo
  57. } // namespace ranges
  58. #endif // _LIBCPP_STD_VER >= 20
  59. _LIBCPP_END_NAMESPACE_STD
  60. #endif // _LIBCPP___ITERATOR_PREV_H