2 //===----------------------------------------------------------------------===//
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
8 //===----------------------------------------------------------------------===//
10 #ifndef _LIBCPP___ITERATOR_DISTANCE_H
11 #define _LIBCPP___ITERATOR_DISTANCE_H
14 #include <__iterator/concepts.h>
15 #include <__iterator/incrementable_traits.h>
16 #include <__iterator/iterator_traits.h>
17 #include <__ranges/access.h>
18 #include <__ranges/concepts.h>
19 #include <__ranges/size.h>
20 #include <__type_traits/decay.h>
21 #include <__type_traits/remove_cvref.h>
23 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
24 # pragma GCC system_header
27 _LIBCPP_BEGIN_NAMESPACE_STD
29 template <class _InputIter
>
30 inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX17 typename iterator_traits
<_InputIter
>::difference_type
31 __distance(_InputIter __first
, _InputIter __last
, input_iterator_tag
) {
32 typename iterator_traits
<_InputIter
>::difference_type
__r(0);
33 for (; __first
!= __last
; ++__first
)
38 template <class _RandIter
>
39 inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX17 typename iterator_traits
<_RandIter
>::difference_type
40 __distance(_RandIter __first
, _RandIter __last
, random_access_iterator_tag
) {
41 return __last
- __first
;
44 template <class _InputIter
>
45 inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX17 typename iterator_traits
<_InputIter
>::difference_type
46 distance(_InputIter __first
, _InputIter __last
) {
47 return std::__distance(__first
, __last
, typename iterator_traits
<_InputIter
>::iterator_category());
50 #if _LIBCPP_STD_VER >= 20
52 // [range.iter.op.distance]
56 template <class _Ip
, sentinel_for
<_Ip
> _Sp
>
57 requires(!sized_sentinel_for
<_Sp
, _Ip
>)
58 _LIBCPP_HIDE_FROM_ABI
constexpr iter_difference_t
<_Ip
> operator()(_Ip __first
, _Sp __last
) const {
59 iter_difference_t
<_Ip
> __n
= 0;
60 while (__first
!= __last
) {
67 template <class _Ip
, sized_sentinel_for
<decay_t
<_Ip
>> _Sp
>
68 _LIBCPP_HIDE_FROM_ABI
constexpr iter_difference_t
<_Ip
> operator()(_Ip
&& __first
, _Sp __last
) const {
69 if constexpr (sized_sentinel_for
<_Sp
, __remove_cvref_t
<_Ip
>>) {
70 return __last
- __first
;
72 return __last
- decay_t
<_Ip
>(__first
);
77 _LIBCPP_HIDE_FROM_ABI
constexpr range_difference_t
<_Rp
> operator()(_Rp
&& __r
) const {
78 if constexpr (sized_range
<_Rp
>) {
79 return static_cast<range_difference_t
<_Rp
>>(ranges::size(__r
));
81 return operator()(ranges::begin(__r
), ranges::end(__r
));
86 inline namespace __cpo
{
87 inline constexpr auto distance
= __distance
{};
91 #endif // _LIBCPP_STD_VER >= 20
93 _LIBCPP_END_NAMESPACE_STD
95 #endif // _LIBCPP___ITERATOR_DISTANCE_H