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