reverse.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #ifndef _LIBCPP___ALGORITHM_REVERSE_H
  9. #define _LIBCPP___ALGORITHM_REVERSE_H
  10. #include <__algorithm/iter_swap.h>
  11. #include <__algorithm/iterator_operations.h>
  12. #include <__config>
  13. #include <__iterator/iterator_traits.h>
  14. #include <__utility/move.h>
  15. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  16. # pragma GCC system_header
  17. #endif
  18. _LIBCPP_BEGIN_NAMESPACE_STD
  19. template <class _AlgPolicy, class _BidirectionalIterator>
  20. inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_SINCE_CXX20
  21. void
  22. __reverse_impl(_BidirectionalIterator __first, _BidirectionalIterator __last, bidirectional_iterator_tag)
  23. {
  24. while (__first != __last)
  25. {
  26. if (__first == --__last)
  27. break;
  28. _IterOps<_AlgPolicy>::iter_swap(__first, __last);
  29. ++__first;
  30. }
  31. }
  32. template <class _AlgPolicy, class _RandomAccessIterator>
  33. inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_SINCE_CXX20
  34. void
  35. __reverse_impl(_RandomAccessIterator __first, _RandomAccessIterator __last, random_access_iterator_tag)
  36. {
  37. if (__first != __last)
  38. for (; __first < --__last; ++__first)
  39. _IterOps<_AlgPolicy>::iter_swap(__first, __last);
  40. }
  41. template <class _AlgPolicy, class _BidirectionalIterator, class _Sentinel>
  42. _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20
  43. void __reverse(_BidirectionalIterator __first, _Sentinel __last) {
  44. using _IterCategory = typename _IterOps<_AlgPolicy>::template __iterator_category<_BidirectionalIterator>;
  45. std::__reverse_impl<_AlgPolicy>(std::move(__first), std::move(__last), _IterCategory());
  46. }
  47. template <class _BidirectionalIterator>
  48. inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_SINCE_CXX20
  49. void
  50. reverse(_BidirectionalIterator __first, _BidirectionalIterator __last)
  51. {
  52. std::__reverse<_ClassicAlgPolicy>(std::move(__first), std::move(__last));
  53. }
  54. _LIBCPP_END_NAMESPACE_STD
  55. #endif // _LIBCPP___ALGORITHM_REVERSE_H