Debian Codegraph @

common/main/d_zip.h

raw
1 /*
2 * This file is part of the DXX-Rebirth project <http://www.dxx-rebirth.com/>.
3 * It is copyright by its individual contributors, as recorded in the
4 * project's Git history. See COPYING.txt at the top level for license
5 * terms and a link to the Git history.
6 */
7 #pragma once
8
9 #include <cstdint>
10 #include <iterator>
11 #include <tuple>
12 #include <type_traits>
13 #include "dxxsconf.h"
14 #include <utility>
15 #include <ranges>
16 #include <span>
17
18 enum class zip_sequence_length_selector : uint32_t;
19
20 template <zip_sequence_length_selector selector>
21 using zip_sequence_selector = std::integral_constant<zip_sequence_length_selector, selector>;
22
23 namespace d_zip {
24
25 namespace detail {
26
27 /* `range_static_extent` stores the extent of a range. If the extent is not
28 * available as an integer constant expression (such as happens for
29 * `std::vector<int>`, which is a range, but the extent of the range can only
30 * be determined at runtime), then `dynamic_extent` is used as a placeholder.
31 */
32 enum class range_static_extent : std::size_t
33 {
34 dynamic_extent = std::dynamic_extent,
35 };
36
37 template <std::ranges::range Range>
38 /* By default, the static size is unknown. */
39 inline constexpr range_static_extent range_static_size{range_static_extent::dynamic_extent};
40
41 template <std::ranges::range Range>
42 /* If the range can be used to construct a `std::span`, then consider the
43 * extent of the range to be the extent of the resulting span. This allows
44 * measuring any range for which `std::span` has an overload, including
45 * C arrays, `std::array`, and `std::span`.
46 *
47 * `std::span` only accepts contiguous ranges. If there are non-contiguous
48 * ranges that can be measured at compile-time, a specialization to cover those
49 * types can be added below.
50 */
51 requires(
52 requires(Range &r) {
53 decltype(std::span(r))::extent;
54 }
55 )
56 inline constexpr range_static_extent range_static_size<Range>{decltype(std::span(std::declval<Range &>()))::extent};
57
58 template <bool ignore, std::ranges::input_range range>
59 static constexpr auto capture_end_iterator(range &&r)
60 {
61 if constexpr (ignore)
62 return std::ignore;
63 else
64 return std::ranges::end(r);
65 }
66
67 template <zip_sequence_length_selector examine_end_range, typename... range_sentinel_type>
68 requires(
69 examine_end_range != zip_sequence_length_selector{} &&
70 sizeof...(range_sentinel_type) > 0
71 )
72 struct zip_sentinel : public std::tuple<range_sentinel_type...>
73 {
74 using selector = zip_sequence_selector<examine_end_range>;
75 template <std::ranges::input_range... rangeN>
76 constexpr explicit zip_sentinel(rangeN &&...r) :
77 std::tuple<range_sentinel_type...>{
78 capture_end_iterator<
79 std::is_same_v<const range_sentinel_type &, const decltype(std::ignore) &>
80 >(r)...
81 }
82 {
83 }
84 };
85
86 template <std::size_t... range_index>
87 struct for_index_sequence
88 {
89 /* This class is never instantiated, but a constructor is declared to
90 * support Class Template Argument Deduction.
91 */
92 for_index_sequence(std::index_sequence<range_index...>);
93 /* Run-time functions. These are defined and called. */
94 template <std::input_or_output_iterator... range_iterator_type>
95 static void increment_iterator(std::tuple<range_iterator_type...> &iterator)
96 {
97 (static_cast<void>(++(std::get<range_index>(iterator))), ...);
98 }
99 template <std::bidirectional_iterator... range_iterator_type>
100 static void decrement_iterator(std::tuple<range_iterator_type...> &iterator)
101 {
102 (static_cast<void>(--(std::get<range_index>(iterator))), ...);
103 }
104 template <std::input_or_output_iterator... range_iterator_type>
105 static auto dereference_iterator(const std::tuple<range_iterator_type...> &iterator);
106 template <typename zip_iterator, zip_sequence_length_selector examine_end_range, typename... zip_sentinel_elements>
107 static constexpr bool compare_zip_iterators(const zip_iterator &iterator, const zip_sentinel<examine_end_range, zip_sentinel_elements...> &sentinel);
108 };
109
110 template <std::size_t... range_index>
111 template <std::input_or_output_iterator... range_iterator_type>
112 auto for_index_sequence<range_index...>::dereference_iterator(const std::tuple<range_iterator_type...> &iterator)
113 {
114 /* std::make_tuple is not appropriate here, because the result of
115 * dereferencing the iterator may be a reference, and the resulting
116 * tuple should store the reference, not the underlying object.
117 * Calling std::make_tuple would decay such references into the
118 * underlying type.
119 *
120 * std::tie is not appropriate here, because it captures all
121 * arguments as `T &`, so it fails to compile if the result of
122 * dereferencing the iterator is not a reference.
123 */
124 return std::tuple<
125 decltype(*(std::get<range_index>(iterator)))...
126 >(*(std::get<range_index>(iterator))...);
127 }
128
129 /* Given a zip_sequence_length_selector and an index N in a sequence, evaluate
130 * to true if the element at index N is examined, and otherwise false.
131 *
132 * This is a convenience variable to keep the test in one place, rather than
133 * duplicating the cast+mask everywhere it is needed.
134 */
135 template <zip_sequence_length_selector examine_end_range, std::size_t N>
136 inline constexpr bool examine_zip_element{(N < 32 && (static_cast<uint32_t>(examine_end_range) & (1u << N)))};
137
138 /* `std::integer_sequence<range_static_extent, N...>` would work here, except
139 * that `range_static_extent` is an `enum class` and gcc-14 requires
140 * `std::is_integral_v<T>` be true for the integer type `T`. `enum class` does
141 * not satisfy `std::is_integral_v`. Therefore, define a custom type to serve
142 * an equivalent purpose to `std::integer_sequence`.
143 */
144 template <range_static_extent... N>
145 struct range_extent_sequence
146 {
147 static constexpr std::size_t size{sizeof...(N)};
148 };
149
150 /* Given a zip_sequence_length_selector and a sequence of static sizes In,
151 * return a new sequence of static sizes `On` where:
152 * - If index N is selected, `On`=`In`.
153 * - Otherwise, `On`=`range_static_extent::dynamic_extent`.
154 *
155 * The output sequence discards static size information for elements that will
156 * not be selected at runtime.
157 */
158 template <zip_sequence_length_selector examine_end_range, std::size_t... indexN, range_static_extent... sizeN>
159 range_extent_sequence<(examine_zip_element<examine_end_range, indexN> ? sizeN : range_static_extent::dynamic_extent) ...> get_examined_static_size(std::index_sequence<indexN...>, range_extent_sequence<sizeN...>);
160
161 /* Yield the lesser of the first size or the next iteration of the template.
162 * Subsequent iterations of the template will fold down the remaining values
163 * until the base case is reached.
164 */
165 template <range_static_extent size0, range_static_extent... sizeN>
166 consteval range_static_extent minimum_static_size(range_extent_sequence<size0, sizeN...>)
167 {
168 if constexpr (sizeof...(sizeN) > 0)
169 return std::min(size0, minimum_static_size(range_extent_sequence<sizeN...>()));
170 else
171 /* A sequence of one element is trivially the size from that element, regardless
172 * of the value of size.
173 */
174 return size0;
175 }
176
177 void range_index_type(...);
178
179 template <
180 typename... range_type,
181 /* If any `range_type::index_type` is not defined, fail.
182 * If there is no common_type among all the
183 * `range_type::index_type`, fail.
184 */
185 typename index_type = typename std::common_type<typename std::remove_reference<typename std::remove_reference<range_type>::type::index_type &>::type...>::type,
186 /* If the common_type `index_type` is not a suitable argument to all
187 * `range_type::operator[]()`, fail.
188 */
189 typename = std::void_t<decltype(std::declval<range_type &>().operator[](std::declval<index_type>()))...>
190 >
191 index_type range_index_type(std::tuple<range_type...> *);
192
193 /* Given as inputs:
194 * - a selector mask
195 * - a tuple of iterator types <In>
196 * - a std::index_sequence of the same length as the tuple
197 *
198 * Produce a type defined as zip_sentinel<On> where On=In if the iterator is
199 * selected in by the mask, and On=std::ignore if the iterator is not selected.
200 * The resulting tuple will then collapse down, avoiding the need to save
201 * non-selected types In in the end iterator.
202 */
203 template <zip_sequence_length_selector examine_end_range, std::ranges::range... range_type, std::size_t... range_index>
204 requires(examine_end_range != zip_sequence_length_selector{} && sizeof...(range_index) == sizeof...(range_type))
205 auto iterator_end_type(std::tuple<range_type...>, std::index_sequence<range_index...>) -> zip_sentinel<
206 examine_end_range,
207 typename std::conditional<
208 examine_zip_element<examine_end_range, range_index>,
209 decltype(std::ranges::end(std::declval<range_type &&>())),
210 decltype(std::ignore)
211 >::type ...
212 >;
213
214 template <bool mask, std::size_t N, typename zip_iterator, typename zip_sentinel>
215 static constexpr auto compare_zip_iterator(const zip_iterator &l, const zip_sentinel &r)
216 {
217 if constexpr (mask)
218 /* For each included member of the iterator, check if the member compares
219 * equal between the two instances. Excluded members use the else
220 * block.
221 */
222 return std::get<N>(l) == std::get<N>(r);
223 else
224 {
225 /* For each excluded member of the iterator, do nothing. Excluded members
226 * are not checked for equality, because excluded members are omitted from
227 * the sentinel, instead of being set to the value of `rangeN.end()`,
228 * so examining such members is not possible.
229 */
230 (void)l;
231 (void)r;
232 return std::false_type{};
233 }
234 }
235
236 template <std::size_t... N>
237 template <typename zip_iterator, zip_sequence_length_selector examine_end_range, typename... zip_sentinel_elements>
238 constexpr bool for_index_sequence<N...>::compare_zip_iterators(const zip_iterator &iterator, const zip_sentinel<examine_end_range, zip_sentinel_elements...> &sentinel)
239 {
240 /* Note the use of `||`, which is atypical for an equality comparison. By
241 * design, a zip iterator should terminate when any of the component
242 * sequences reaches its end, so use of `||` is correct for that purpose.
243 */
244 return (compare_zip_iterator<examine_zip_element<examine_end_range, N>, N>(iterator, sentinel) || ... || false);
245 }
246
247 }
248
249 }
250
251 /* This iterator terminates when the selected zipped range(s) terminate. The
252 * caller is responsible for ensuring that use of the zip_iterator does
253 * not increment past the end of any zipped range. This can be done by
254 * ensuring that the selected zipped range(s) are not longer than any ignored
255 * zipped range, or by ensuring that external logic stops the traversal
256 * before the zip_iterator increments past the end.
257 *
258 * There is no runtime check that the below loop would be
259 * safe, since a check external to the zip_iterator could stop before
260 * undefined behaviour occurs.
261 *
262 * However, if any selected range is convertible to a C array of known
263 * length or to a C++ std::array, then there is a compile-time check
264 * that the shortest selected range is not longer than any other range that is
265 * likewise convertible. If a range cannot be converted to an array,
266 * then its length is unknown and is not checked. If the first range is
267 * not convertible, then no ranges are checked.
268
269 for (auto i = zip_range.begin(), e = zip_range.end(); i != e; ++i)
270 {
271 if (condition())
272 break;
273 }
274
275 */
276 template <typename range_iterator_tuple, typename range_sentinel_type>
277 class zip_iterator;
278
279 template <std::input_or_output_iterator... range_iterator_types, typename range_sentinel_type>
280 class zip_iterator<std::tuple<range_iterator_types...>, range_sentinel_type> : std::tuple<range_iterator_types...>
281 {
282 using range_iterator_tuple = std::tuple<range_iterator_types...>;
283 protected:
284 using for_index_sequence = decltype(d_zip::detail::for_index_sequence(std::make_index_sequence<sizeof...(range_iterator_types)>()));
285 public:
286 using range_iterator_tuple::range_iterator_tuple;
287 using difference_type = typename std::incrementable_traits<
288 typename std::remove_reference_t<
289 std::tuple_element_t<0, range_iterator_tuple>
290 >>::difference_type;
291 using value_type = decltype(for_index_sequence::dereference_iterator(std::declval<range_iterator_tuple>()));
292 using pointer = value_type *;
293 using reference = value_type &;
294 /*
295 * Given a tuple of iterator types, return the most-derived iterator_category
296 * that all the iterator types satisfy.
297 */
298 using iterator_category = typename std::common_type<typename std::iterator_traits<range_iterator_types>::iterator_category...>::type;
299 auto operator*() const
300 {
301 return for_index_sequence::dereference_iterator(static_cast<const range_iterator_tuple &>(*this));
302 }
303 zip_iterator &operator++()
304 {
305 for_index_sequence::increment_iterator(static_cast<range_iterator_tuple &>(*this));
306 return *this;
307 }
308 /* operator++(int) is currently unused, but is required to satisfy
309 * the concept check on forward iterator.
310 */
311 zip_iterator operator++(int)
312 {
313 auto result{*this};
314 ++ *this;
315 return result;
316 }
317 zip_iterator &operator--()
318 requires(
319 requires(range_iterator_tuple i) {
320 for_index_sequence::decrement_iterator(i);
321 }
322 )
323 {
324 for_index_sequence::decrement_iterator(static_cast<range_iterator_tuple &>(*this));
325 return *this;
326 }
327 zip_iterator operator--(int)
328 requires(
329 requires(zip_iterator i) {
330 -- i;
331 }
332 )
333 {
334 auto result{*this};
335 -- *this;
336 return result;
337 }
338 auto operator-(const zip_iterator &i) const
339 requires(
340 std::derived_from<iterator_category, std::random_access_iterator_tag> &&
341 requires(range_iterator_tuple i) {
342 std::get<0>(i) - std::get<0>(i);
343 }
344 )
345 {
346 return std::get<0>(static_cast<const range_iterator_tuple &>(*this)) - std::get<0>(static_cast<const range_iterator_tuple &>(i));
347 }
348 constexpr bool operator==(const zip_iterator &) const = default;
349 constexpr bool operator==(const range_sentinel_type &i) const
350 {
351 return for_index_sequence::template compare_zip_iterators<range_iterator_tuple>(*this, i);
352 }
353 };
354
355 template <
356 zip_sequence_length_selector examine_end_range,
357 /* Values in `range_all_static_sizes` are either a `range_static_extent`
358 * reporting the static size of the corresponding range, or
359 * `range_static_extent::dynamic_extent` if the range has no known
360 * static size.
361 */
362 typename range_all_static_sizes, // range_extent_sequence<Extent...>
363 /* Value `minimum_all_static_size` is the `range_static_extent`
364 * reporting the static size of the shortest static range, or
365 * `range_static_extent::dynamic_extent` if no ranges have a known
366 * static size.
367 */
368 d_zip::detail::range_static_extent minimum_all_static_size = d_zip::detail::minimum_static_size(range_all_static_sizes()),
369 /* Filter `range_all_static_sizes` to discard static sizes for elements
370 * that will not be examined at runtime.
371 */
372 typename range_examined_static_sizes = decltype(d_zip::detail::get_examined_static_size<examine_end_range>(std::make_index_sequence<range_all_static_sizes::size>(), range_all_static_sizes())),
373 /* Value `minimum_examined_static_size` reports the static size of the
374 * shortest examined static range, or `range_static_extent::dynamic_extent`
375 * if no examined ranges have a known static size.
376 */
377 d_zip::detail::range_static_extent minimum_examined_static_size = d_zip::detail::minimum_static_size(range_examined_static_sizes())
378 >
379 concept zip_static_size_bounds_check = (
380 /* If no examined range has a static size, then
381 * `minimum_examined_static_size` is
382 * `range_static_extent::dynamic_extent` and no compile-time check is
383 * possible.
384 *
385 * Otherwise, at least one examined range has a static size, so check
386 * that it is not longer than an unexamined static range.
387 */
388 (minimum_examined_static_size == d_zip::detail::range_static_extent::dynamic_extent || minimum_examined_static_size <= minimum_all_static_size)
389 );
390
391 template <
392 zip_sequence_length_selector examine_end_range,
393 typename... rangeN
394 >
395 concept zip_input_constraints = (
396 /* Require at least two ranges. A zip of a single range adds complexity for no reason. */
397 sizeof...(rangeN) > 1 &&
398 (std::ranges::input_range<rangeN> && ...) &&
399 /* Require borrowed ranges, because zip will return iterators that point into the ranges. */
400 (std::ranges::borrowed_range<rangeN> && ...) &&
401 zip_static_size_bounds_check<
402 examine_end_range,
403 d_zip::detail::range_extent_sequence<d_zip::detail::range_static_size<rangeN>...>
404 >
405 );
406
407 /* Class Template Argument Deduction cannot implicitly deduce the template type
408 * arguments for `zip` because none of the types are used directly as an
409 * argument to any constructor, but instead are derived from properties of the
410 * constructor arguments.
411 *
412 * Explicit deduction guides are provided below to handle constructing `zip`
413 * without specifying template argument types.
414 */
415 template <typename range_index_type, typename range_iterator_type, typename sentinel_type>
416 struct zip : std::ranges::subrange<zip_iterator<range_iterator_type, sentinel_type>, sentinel_type>
417 {
418 using index_type = range_index_type;
419 using iterator = zip_iterator<range_iterator_type, sentinel_type>;
420 template <std::ranges::input_range... rangeN>
421 requires(
422 zip_input_constraints<sentinel_type::selector::value, rangeN...>
423 )
424 constexpr zip(rangeN &&... rN) :
425 std::ranges::subrange<iterator, sentinel_type>{iterator{std::ranges::begin(rN)...}, sentinel_type{rN...}}
426 {
427 }
428 template <std::ranges::input_range... rangeN>
429 /* Delegate to the no-selector constructor, since the selector is not
430 * needed by the constructor. The selector affected the type of
431 * `zip_sentinel_type`, which in turn affects how `m_end` is
432 * constructed.
433 */
434 constexpr zip(sentinel_type::selector, rangeN &&... rN) :
435 zip{std::forward<rangeN>(rN)...}
436 {
437 }
438 };
439
440 /* zip() is always a view onto another range, and never owns the storage that
441 * its iterators reference. */
442 template <typename range_index_type, typename range_iterator_type, typename range_sentinel_type>
443 inline constexpr bool std::ranges::enable_borrowed_range<zip<range_index_type, range_iterator_type, range_sentinel_type>> = true;
444
445 template <zip_sequence_length_selector examine_end_range, std::ranges::input_range... rangeN>
446 requires(
447 zip_input_constraints<examine_end_range, rangeN...>
448 )
449 zip(zip_sequence_selector<examine_end_range>, rangeN &&... rN) -> zip<
450 /* range_index_type = */ decltype(d_zip::detail::range_index_type(static_cast<std::tuple<rangeN...> *>(nullptr))),
451 /* range_iterator_type = */ std::tuple<decltype(std::ranges::begin(std::declval<rangeN &&>()))...>,
452 /* range_sentinel_type = */ decltype(
453 d_zip::detail::iterator_end_type<examine_end_range>(
454 std::declval<std::tuple<rangeN...>>(),
455 std::make_index_sequence<sizeof...(rangeN)>()
456 )
457 )
458 >;
459
460 /* Store the default selector as a default template argument, so that the
461 * template-id specified by the deduction guide can use the same text in both
462 * the explicit-selector and implicit-selector guides.
463 */
464 template <std::ranges::input_range... rangeN, zip_sequence_length_selector examine_end_range = zip_sequence_length_selector{1}>
465 requires(
466 zip_input_constraints<examine_end_range, rangeN...>
467 )
468 zip(rangeN &&... rN) -> zip<
469 /* range_index_type = */ decltype(d_zip::detail::range_index_type(static_cast<std::tuple<rangeN...> *>(nullptr))),
470 /* range_iterator_type = */ std::tuple<decltype(std::ranges::begin(std::declval<rangeN &&>()))...>,
471 /* range_sentinel_type = */ decltype(
472 d_zip::detail::iterator_end_type<examine_end_range>(
473 std::declval<std::tuple<rangeN...>>(),
474 std::make_index_sequence<sizeof...(rangeN)>()
475 )
476 )
477 >;