xref: /llvm-project/libcxx/include/__ranges/to.h (revision 811186764d1add4d83972db3ad0d2e7c96bb15a7)
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___RANGES_TO_H
11 #define _LIBCPP___RANGES_TO_H
12 
13 #include <__concepts/constructible.h>
14 #include <__concepts/convertible_to.h>
15 #include <__concepts/derived_from.h>
16 #include <__concepts/same_as.h>
17 #include <__config>
18 #include <__cstddef/ptrdiff_t.h>
19 #include <__functional/bind_back.h>
20 #include <__iterator/iterator_traits.h>
21 #include <__ranges/access.h>
22 #include <__ranges/concepts.h>
23 #include <__ranges/from_range.h>
24 #include <__ranges/range_adaptor.h>
25 #include <__ranges/ref_view.h>
26 #include <__ranges/size.h>
27 #include <__ranges/transform_view.h>
28 #include <__type_traits/add_pointer.h>
29 #include <__type_traits/is_const.h>
30 #include <__type_traits/is_volatile.h>
31 #include <__type_traits/type_identity.h>
32 #include <__utility/declval.h>
33 #include <__utility/forward.h>
34 
35 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
36 #  pragma GCC system_header
37 #endif
38 
39 _LIBCPP_BEGIN_NAMESPACE_STD
40 
41 #if _LIBCPP_STD_VER >= 23
42 
43 namespace ranges {
44 
45 template <class _Container>
46 constexpr bool __reservable_container =
47     sized_range<_Container> && requires(_Container& __c, range_size_t<_Container> __n) {
48       __c.reserve(__n);
49       { __c.capacity() } -> same_as<decltype(__n)>;
50       { __c.max_size() } -> same_as<decltype(__n)>;
51     };
52 
53 template <class _Container, class _Ref>
54 constexpr bool __container_appendable = requires(_Container& __c, _Ref&& __ref) {
55   requires(
56       requires { __c.emplace_back(std::forward<_Ref>(__ref)); } ||
57       requires { __c.push_back(std::forward<_Ref>(__ref)); } ||
58       requires { __c.emplace(__c.end(), std::forward<_Ref>(__ref)); } ||
59       requires { __c.insert(__c.end(), std::forward<_Ref>(__ref)); });
60 };
61 
62 // Note: making this a concept allows short-circuiting the second condition.
63 template <class _Container, class _Range>
64 concept __try_non_recursive_conversion =
65     !input_range<_Container> || convertible_to<range_reference_t<_Range>, range_value_t<_Container>>;
66 
67 template <class _Container, class _Range, class... _Args>
68 concept __constructible_from_iter_pair =
69     common_range<_Range> && requires { typename iterator_traits<iterator_t<_Range>>::iterator_category; } &&
70     derived_from<typename iterator_traits<iterator_t<_Range>>::iterator_category, input_iterator_tag> &&
71     constructible_from<_Container, iterator_t<_Range>, sentinel_t<_Range>, _Args...>;
72 
73 template <class>
74 concept __always_false = false;
75 
76 // `ranges::to` base template -- the `_Container` type is a simple type template parameter.
77 template <class _Container, input_range _Range, class... _Args>
78   requires(!view<_Container>)
79 [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr _Container to(_Range&& __range, _Args&&... __args) {
80   // Mandates: C is a cv-unqualified class type.
81   static_assert(!is_const_v<_Container>, "The target container cannot be const-qualified, please remove the const");
82   static_assert(
83       !is_volatile_v<_Container>, "The target container cannot be volatile-qualified, please remove the volatile");
84 
85   // First see if the non-recursive case applies -- the conversion target is either:
86   // - a range with a convertible value type;
87   // - a non-range type which might support being created from the input argument(s) (e.g. an `optional`).
88   if constexpr (__try_non_recursive_conversion<_Container, _Range>) {
89     // Case 1 -- construct directly from the given range.
90     if constexpr (constructible_from<_Container, _Range, _Args...>) {
91       return _Container(std::forward<_Range>(__range), std::forward<_Args>(__args)...);
92     }
93 
94     // Case 2 -- construct using the `from_range_t` tagged constructor.
95     else if constexpr (constructible_from<_Container, from_range_t, _Range, _Args...>) {
96       return _Container(from_range, std::forward<_Range>(__range), std::forward<_Args>(__args)...);
97     }
98 
99     // Case 3 -- construct from a begin-end iterator pair.
100     else if constexpr (__constructible_from_iter_pair<_Container, _Range, _Args...>) {
101       return _Container(ranges::begin(__range), ranges::end(__range), std::forward<_Args>(__args)...);
102     }
103 
104     // Case 4 -- default-construct (or construct from the extra arguments) and insert, reserving the size if possible.
105     else if constexpr (constructible_from<_Container, _Args...> &&
106                        __container_appendable<_Container, range_reference_t<_Range>>) {
107       _Container __result(std::forward<_Args>(__args)...);
108       if constexpr (sized_range<_Range> && __reservable_container<_Container>) {
109         __result.reserve(static_cast<range_size_t<_Container>>(ranges::size(__range)));
110       }
111 
112       for (auto&& __ref : __range) {
113         using _Ref = decltype(__ref);
114         if constexpr (requires { __result.emplace_back(std::declval<_Ref>()); }) {
115           __result.emplace_back(std::forward<_Ref>(__ref));
116         } else if constexpr (requires { __result.push_back(std::declval<_Ref>()); }) {
117           __result.push_back(std::forward<_Ref>(__ref));
118         } else if constexpr (requires { __result.emplace(__result.end(), std::declval<_Ref>()); }) {
119           __result.emplace(__result.end(), std::forward<_Ref>(__ref));
120         } else {
121           static_assert(requires { __result.insert(__result.end(), std::declval<_Ref>()); });
122           __result.insert(__result.end(), std::forward<_Ref>(__ref));
123         }
124       }
125       return __result;
126 
127     } else {
128       static_assert(__always_false<_Container>, "ranges::to: unable to convert to the given container type.");
129     }
130 
131     // Try the recursive case.
132   } else if constexpr (input_range<range_reference_t<_Range>>) {
133     return ranges::to<_Container>(
134         ref_view(__range) | views::transform([](auto&& __elem) {
135           return ranges::to<range_value_t<_Container>>(std::forward<decltype(__elem)>(__elem));
136         }),
137         std::forward<_Args>(__args)...);
138 
139   } else {
140     static_assert(__always_false<_Container>, "ranges::to: unable to convert to the given container type.");
141   }
142 }
143 
144 template <class _Range>
145 struct __minimal_input_iterator {
146   using iterator_category = input_iterator_tag;
147   using value_type        = range_value_t<_Range>;
148   using difference_type   = ptrdiff_t;
149   using pointer           = add_pointer_t<range_reference_t<_Range>>;
150   using reference         = range_reference_t<_Range>;
151 
152   reference operator*() const;
153   pointer operator->() const;
154   __minimal_input_iterator& operator++();
155   __minimal_input_iterator operator++(int);
156   bool operator==(const __minimal_input_iterator&) const;
157 };
158 
159 // Deduces the full type of the container from the given template template parameter.
160 template <template <class...> class _Container, input_range _Range, class... _Args>
161 struct _Deducer {
162   _LIBCPP_HIDE_FROM_ABI static constexpr auto __deduce_func() {
163     using _InputIter = __minimal_input_iterator<_Range>;
164 
165     // Case 1 -- can construct directly from the given range.
166     if constexpr (requires { _Container(std::declval<_Range>(), std::declval<_Args>()...); }) {
167       using _Result = decltype( //
168           _Container(std::declval<_Range>(), std::declval<_Args>()...));
169       return type_identity<_Result>{};
170 
171       // Case 2 -- can construct from the given range using the `from_range_t` tagged constructor.
172     } else if constexpr ( //
173         requires { _Container(from_range, std::declval<_Range>(), std::declval<_Args>()...); }) {
174       using _Result = //
175           decltype(_Container(from_range, std::declval<_Range>(), std::declval<_Args>()...));
176       return type_identity<_Result>{};
177 
178       // Case 3 -- can construct from a begin-end iterator pair.
179     } else if constexpr ( //
180         requires { _Container(std::declval<_InputIter>(), std::declval<_InputIter>(), std::declval<_Args>()...); }) {
181       using _Result =
182           decltype(_Container(std::declval<_InputIter>(), std::declval<_InputIter>(), std::declval<_Args>()...));
183       return type_identity<_Result>{};
184 
185     } else {
186       static_assert(__always_false<_Range>,
187                     "ranges::to: unable to deduce the container type from the template template argument.");
188     }
189   }
190 
191   using type = typename decltype(__deduce_func())::type;
192 };
193 
194 // `ranges::to` specialization -- `_Container` is a template template parameter requiring deduction to figure out the
195 // container element type.
196 template <template <class...> class _Container, input_range _Range, class... _Args>
197 [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr auto to(_Range&& __range, _Args&&... __args) {
198   using _DeduceExpr = typename _Deducer<_Container, _Range, _Args...>::type;
199   return ranges::to<_DeduceExpr>(std::forward<_Range>(__range), std::forward<_Args>(__args)...);
200 }
201 
202 // Range adaptor closure object 1 -- wrapping the `ranges::to` version where `_Container` is a simple type template
203 // parameter.
204 template <class _Container, class... _Args>
205   requires(!view<_Container>)
206 [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr auto to(_Args&&... __args) {
207   // Mandates: C is a cv-unqualified class type.
208   static_assert(!is_const_v<_Container>, "The target container cannot be const-qualified, please remove the const");
209   static_assert(
210       !is_volatile_v<_Container>, "The target container cannot be volatile-qualified, please remove the volatile");
211 
212   auto __to_func = []<input_range _Range, class... _Tail>(_Range&& __range, _Tail&&... __tail) static
213     requires requires { //
214       /**/ ranges::to<_Container>(std::forward<_Range>(__range), std::forward<_Tail>(__tail)...);
215     }
216   { return ranges::to<_Container>(std::forward<_Range>(__range), std::forward<_Tail>(__tail)...); };
217 
218   return __pipeable(std::__bind_back(__to_func, std::forward<_Args>(__args)...));
219 }
220 
221 // Range adaptor closure object 2 -- wrapping the `ranges::to` version where `_Container` is a template template
222 // parameter.
223 template <template <class...> class _Container, class... _Args>
224 [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr auto to(_Args&&... __args) {
225   // clang-format off
226   auto __to_func = []<input_range _Range, class... _Tail,
227                       class _DeducedExpr = typename _Deducer<_Container, _Range, _Tail...>::type>
228     (_Range&& __range, _Tail&& ... __tail) static
229       requires requires { //
230       /**/ ranges::to<_DeducedExpr>(std::forward<_Range>(__range), std::forward<_Tail>(__tail)...);
231     }
232   {
233     return ranges::to<_DeducedExpr>(std::forward<_Range>(__range), std::forward<_Tail>(__tail)...);
234   };
235   // clang-format on
236 
237   return __pipeable(std::__bind_back(__to_func, std::forward<_Args>(__args)...));
238 }
239 
240 } // namespace ranges
241 
242 #endif // _LIBCPP_STD_VER >= 23
243 
244 _LIBCPP_END_NAMESPACE_STD
245 
246 #endif // _LIBCPP___RANGES_TO_H
247