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_INCREMENTABLE_TRAITS_H
11#define _LIBCPP___ITERATOR_INCREMENTABLE_TRAITS_H
12
13#include <__config>
14#include <concepts>
15#include <type_traits>
16
17#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
18#pragma GCC system_header
19#endif
20
21_LIBCPP_PUSH_MACROS
22#include <__undef_macros>
23
24_LIBCPP_BEGIN_NAMESPACE_STD
25
26#if !defined(_LIBCPP_HAS_NO_RANGES)
27
28// [incrementable.traits]
29template<class> struct incrementable_traits {};
30
31template<class _Tp>
32requires is_object_v<_Tp>
33struct incrementable_traits<_Tp*> {
34  using difference_type = ptrdiff_t;
35};
36
37template<class _Ip>
38struct incrementable_traits<const _Ip> : incrementable_traits<_Ip> {};
39
40template<class _Tp>
41concept __has_member_difference_type = requires { typename _Tp::difference_type; };
42
43template<__has_member_difference_type _Tp>
44struct incrementable_traits<_Tp> {
45  using difference_type = typename _Tp::difference_type;
46};
47
48template<class _Tp>
49concept __has_integral_minus =
50  requires(const _Tp& __x, const _Tp& __y) {
51    { __x - __y } -> integral;
52  };
53
54template<__has_integral_minus _Tp>
55requires (!__has_member_difference_type<_Tp>)
56struct incrementable_traits<_Tp> {
57  using difference_type = make_signed_t<decltype(declval<_Tp>() - declval<_Tp>())>;
58};
59
60template <class>
61struct iterator_traits;
62
63// Let `RI` be `remove_cvref_t<I>`. The type `iter_difference_t<I>` denotes
64// `incrementable_traits<RI>::difference_type` if `iterator_traits<RI>` names a specialization
65// generated from the primary template, and `iterator_traits<RI>::difference_type` otherwise.
66template <class _Ip>
67using iter_difference_t = typename conditional_t<__is_primary_template<iterator_traits<remove_cvref_t<_Ip> > >::value,
68                                                 incrementable_traits<remove_cvref_t<_Ip> >,
69                                                 iterator_traits<remove_cvref_t<_Ip> > >::difference_type;
70
71#endif // !defined(_LIBCPP_HAS_NO_RANGES)
72
73_LIBCPP_END_NAMESPACE_STD
74
75_LIBCPP_POP_MACROS
76
77#endif // _LIBCPP___ITERATOR_INCREMENTABLE_TRAITS_H
78