Debian Codegraph @

common/include/partial_range.h

raw
1 /*
2 * This file is part of the DXX-Rebirth project <https://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 #include <array>
9 #include <stdexcept>
10 #include <iterator>
11 #include <cstdio>
12 #include <string>
13 #include <type_traits>
14 #include <ranges>
15 #include "fwd-partial_range.h"
16 #include <memory>
17 #include "dxxsconf.h"
18
19 /* If no value was specified for DXX_PARTIAL_RANGE_MINIMIZE_ERROR_TYPE,
20 * then define it to true for NDEBUG builds and false for debug builds.
21 *
22 * When DXX_PARTIAL_RANGE_MINIMIZE_ERROR_TYPE is true, the partial_range
23 * exception is a global scope structure.
24 *
25 * When DXX_PARTIAL_RANGE_MINIMIZE_ERROR_TYPE is false, the
26 * partial_range exception is nested in partial_range_t<I>, so that the
27 * exception type encodes the range type.
28 *
29 * Encoding the range type in the exception produces a more descriptive
30 * message when the program aborts for an uncaught exception, but
31 * produces larger debug information and many nearly-redundant
32 * instantiations of the report function. Using the global scope
33 * structure avoids those redundant instances, but makes the exception
34 * description less descriptive.
35 *
36 * Choose false if you expect to debug partial_range exceptions or
37 * report them to someone who will debug them for you. Choose true if
38 * you want a smaller program.
39 */
40 #ifndef DXX_PARTIAL_RANGE_MINIMIZE_ERROR_TYPE
41 #ifdef NDEBUG
42 #define DXX_PARTIAL_RANGE_MINIMIZE_ERROR_TYPE 1
43 #else
44 #define DXX_PARTIAL_RANGE_MINIMIZE_ERROR_TYPE 0
45 #endif
46 #endif
47
48 namespace partial_range_detail {
49
50 #define REPORT_FORMAT_STRING "%s:%u: %s %lu past %p end %lu \"%s\""
51 /* Given the length of a filename (in `NF`) and the length of an
52 * expression to report (in `NE`), compute the required size of a buffer
53 * that can hold the result of applying REPORT_FORMAT_STRING. This
54 * overestimates the size since sizeof(REPORT_FORMAT_STRING) is used
55 * without accounting for the %-escapes being replaced with the expanded
56 * text, and all expansions are assumed to be of maximum length.
57 *
58 * Round reporting into large buckets. Code size is more important than
59 * stack space on a cold path.
60 */
61 template <std::size_t NF, std::size_t NE>
62 constexpr std::size_t required_buffer_size{((sizeof(REPORT_FORMAT_STRING) + sizeof("65535") + (sizeof("18446744073709551615") * 2) + sizeof("0x0000000000000000") + (NF + NE + sizeof("begin"))) | 0xff) + 1};
63
64 template <std::size_t N>
65 /* This is only used on a path that will throw an exception, so mark
66 * it as cold. In a program with no bugs, which is given no
67 * ill-formed data on input, these exceptions never happen.
68 */
69 dxx_compiler_attribute_cold
70 std::string prepare_error_string(const unsigned long d, const char *const estr, const char *const file, const unsigned line, const char *const desc, const unsigned long expr, const uintptr_t t)
71 {
72 std::array<char, N> buf;
73 const auto bufdata{std::data(buf)};
74 const auto bufsize{std::size(buf)};
75 const auto written{std::snprintf(bufdata, bufsize, REPORT_FORMAT_STRING, file, line, desc, expr, reinterpret_cast<const void *>(t), d, estr)};
76 return {bufdata, written < 0 ? 0 : std::min(bufsize, static_cast<std::size_t>(written))};
77 }
78 #undef REPORT_FORMAT_STRING
79
80 template <std::ranges::borrowed_range>
81 void range_index_type(...);
82
83 template <
84 std::ranges::random_access_range range_type,
85 /* If `range_type::index_type` is not defined, fail.
86 */
87 typename index_type = typename std::remove_reference_t<range_type>::index_type
88 /* If `range_type::index_type` is not a suitable argument to
89 * range_type::operator[](), fail.
90 */
91 >
92 requires(
93 std::ranges::borrowed_range<range_type> &&
94 requires(range_type &&r, index_type i) {
95 r[i];
96 }
97 )
98 index_type range_index_type(std::nullptr_t);
99
100 }
101
102 #if DXX_PARTIAL_RANGE_MINIMIZE_ERROR_TYPE
103 struct partial_range_error;
104 #endif
105
106 template <std::input_or_output_iterator range_iterator, typename range_index_type>
107 class partial_range_t : std::ranges::subrange<range_iterator>
108 {
109 using base_type = std::ranges::subrange<range_iterator>;
110 public:
111 static_assert(!std::is_reference<range_iterator>::value);
112 using iterator = range_iterator;
113 using index_type = range_index_type;
114 /* When using the unminimized type, forward declare a structure.
115 *
116 * When using the minimized type, add a typedef here so that later
117 * code can unconditionally use the qualified type name. Using a
118 * typedef here instead of a preprocessor macro at the usage sites
119 * causes the debug information to be very slightly bigger, but has
120 * no effect on the size of the generated code and is easier to
121 * maintain.
122 */
123 #if DXX_PARTIAL_RANGE_MINIMIZE_ERROR_TYPE
124 using partial_range_error =
125 #endif
126 struct partial_range_error;
127 using base_type::base_type;
128 partial_range_t(const partial_range_t &) = default;
129 partial_range_t(partial_range_t &&) = default;
130 partial_range_t &operator=(const partial_range_t &) = default;
131 using base_type::begin;
132 using base_type::end;
133 using base_type::empty;
134 using base_type::size;
135 [[nodiscard]]
136 std::reverse_iterator<iterator> rbegin() const
137 {
138 return std::reverse_iterator<iterator>{end()};
139 }
140 [[nodiscard]]
141 std::reverse_iterator<iterator> rend() const
142 {
143 return std::reverse_iterator<iterator>{begin()};
144 }
145 [[nodiscard]]
146 partial_range_t<std::reverse_iterator<iterator>, index_type> reversed() const
147 {
148 return {rbegin(), rend()};
149 }
150 };
151
152 template <std::input_or_output_iterator range_iterator, typename range_index_type>
153 inline constexpr bool std::ranges::enable_borrowed_range<partial_range_t<range_iterator, range_index_type>> = std::ranges::enable_borrowed_range<std::ranges::subrange<range_iterator>>;
154
155 #if DXX_PARTIAL_RANGE_MINIMIZE_ERROR_TYPE
156 struct partial_range_error
157 #else
158 template <std::input_or_output_iterator range_iterator, typename range_index_type>
159 struct partial_range_t<range_iterator, range_index_type>::partial_range_error
160 #endif
161 final : std::out_of_range
162 {
163 using std::out_of_range::out_of_range;
164 template <std::size_t N>
165 [[noreturn]]
166 dxx_compiler_attribute_cold
167 static void report(const char *file, unsigned line, const char *estr, const char *desc, unsigned long expr, const uintptr_t t, unsigned long d)
168 {
169 throw partial_range_error(partial_range_detail::prepare_error_string<N>(d, estr, file, line, desc, expr, t));
170 }
171 };
172
173 namespace partial_range_detail {
174
175 template <typename range_exception, std::size_t required_buffer_size>
176 dxx_compiler_attribute_always_inline()
177 inline void check_range_bounds(const char *file, unsigned line, const char *estr, const uintptr_t t, const std::size_t index_begin, const std::size_t index_end, const std::size_t d)
178 {
179 #ifdef DXX_CONSTANT_TRUE
180 /*
181 * If EXPR and d are compile-time constant, and the (EXPR > d)
182 * branch is optimized out, then the expansion of
183 * PARTIAL_RANGE_COMPILE_CHECK_BOUND is optimized out, preventing
184 * the compile error.
185 *
186 * If EXPR and d are compile-time constant, and the (EXPR > d)
187 * branch is not optimized out, then this function is guaranteed to
188 * throw if it is ever called. In that case, the compile fails,
189 * since the program is guaranteed not to work as the programmer
190 * intends.
191 *
192 * If they are not compile-time constant, but the compiler can
193 * optimize based on constants, then it will optimize out the
194 * expansion of PARTIAL_RANGE_COMPILE_CHECK_BOUND, preventing the
195 * compile error. The function might throw on invalid inputs,
196 * including constant inputs that the compiler failed to recognize
197 * as compile-time constant.
198 *
199 * If the compiler cannot optimize based on the result of
200 * __builtin_constant_p (such as at -O0), then configure tests do
201 * not define DXX_CONSTANT_TRUE and the macro expands to nothing.
202 */
203 #define PARTIAL_RANGE_COMPILE_CHECK_BOUND(EXPR,S) \
204 (DXX_CONSTANT_TRUE(EXPR > d) && (DXX_ALWAYS_ERROR_FUNCTION(#S " will always throw"), 0))
205 #else
206 #define PARTIAL_RANGE_COMPILE_CHECK_BOUND(EXPR,S) static_cast<void>(0)
207 #endif
208 #define PARTIAL_RANGE_CHECK_BOUND(EXPR,S) \
209 PARTIAL_RANGE_COMPILE_CHECK_BOUND(EXPR,S), \
210 ((EXPR > d) && (range_exception::template report<required_buffer_size>(file, line, estr, #S, EXPR, t, d), 0))
211 PARTIAL_RANGE_CHECK_BOUND(index_begin, begin);
212 PARTIAL_RANGE_CHECK_BOUND(index_end, end);
213 #undef PARTIAL_RANGE_CHECK_BOUND
214 #undef PARTIAL_RANGE_COMPILE_CHECK_BOUND
215 }
216
217 #if DXX_HAVE_BUILTIN_OBJECT_SIZE
218 template <typename range_exception, std::size_t required_buffer_size, typename P>
219 dxx_compiler_attribute_always_inline()
220 inline void check_range_object_size(const char *file, unsigned line, const char *estr, P &ref, const std::size_t index_begin, const std::size_t index_end)
221 {
222 const auto ptr{std::addressof(ref)};
223 /* Get the size of the object, according to the compiler's data
224 * analysis. If a size is known, check that the index values are in
225 * range. If no size is known, do nothing.
226 *
227 * The compiler may return a value of "unknown" here if the target
228 * object is dynamically allocated with unknown extents, or if the
229 * optimizer is not able to identify a specific object behind the
230 * pointer. The latter could happen if the object has a fixed size
231 * assigned in a different translation unit, and only the pointer to
232 * the object is visible in the translation unit evaluating this
233 * function.
234 */
235 const std::size_t bos{__builtin_object_size(ptr, 1)};
236 if (bos != static_cast<std::size_t>(-1))
237 check_range_bounds<range_exception, required_buffer_size>(file, line, estr, reinterpret_cast<uintptr_t>(ptr), index_begin, index_end, bos / sizeof(P));
238 }
239
240 /* When P refers to a temporary, this overload is picked. Temporaries
241 * have no useful address, so they cannot be checked. A temporary would
242 * be present if iterator.operator*() returns a proxy object, rather
243 * than a reference to an element in the container.
244 */
245 template <typename range_exception, std::size_t required_buffer_size>
246 void check_range_object_size(const char *, unsigned, const char *, const auto &&, std::size_t, std::size_t) {}
247 #endif
248
249 /* If no range_type::index_type is defined, then allow any index type. */
250 std::true_type check_range_index_type_vs_provided_index_type(...);
251
252 template <
253 typename range_type,
254 typename provided_index_type,
255 /* If `range_type::index_type` is not defined, fail.
256 * If `range_type::index_type` is void, fail.
257 */
258 typename range_index_type = typename std::remove_reference<typename range_type::index_type &>::type
259 >
260 std::is_same<provided_index_type, range_index_type> check_range_index_type_vs_provided_index_type(const range_type *, const provided_index_type *);
261
262 template <typename range_type, typename index_type>
263 requires(std::is_enum<index_type>::value)
264 std::size_t cast_index_to_size(const index_type i)
265 {
266 static_assert(std::is_unsigned<typename std::underlying_type<index_type>::type>::value, "underlying_type of index_type must be unsigned");
267 /* If an enumerated index type is used, require that it be the type that
268 * the underlying range uses.
269 */
270 static_assert(decltype(check_range_index_type_vs_provided_index_type(static_cast<typename std::remove_reference<range_type>::type *>(nullptr), static_cast<index_type *>(nullptr)))::value);
271 return {static_cast<typename std::underlying_type<index_type>::type>(i)};
272 }
273
274 template <typename range_type, std::unsigned_integral index_type /* integral index_type must be unsigned */>
275 std::size_t cast_index_to_size(const index_type i)
276 {
277 /* Omit enforcement of range_type::index_type vs index_type, since many
278 * call sites provide numeric length limits.
279 static_assert(decltype(check_range_index_type_vs_provided_index_type<range_type, index_type>(nullptr))::value);
280 */
281 /* Use an implicit conversion, so that an index_type of std::size_t does
282 * not cause a useless cast.
283 */
284 return i;
285 }
286
287 }
288
289 template <
290 #if DXX_HAVE_BUILTIN_OBJECT_SIZE
291 std::size_t required_buffer_size,
292 #endif
293 typename index_type,
294 std::input_or_output_iterator iterator_type
295 >
296 [[nodiscard]]
297 inline partial_range_t<iterator_type, index_type> unchecked_partial_range_advance(
298 #if DXX_HAVE_BUILTIN_OBJECT_SIZE
299 const char *const file, const unsigned line, const char *const estr,
300 #endif
301 iterator_type range_begin, const std::size_t index_begin, const std::size_t index_end)
302 {
303 #ifdef DXX_CONSTANT_TRUE
304 /* Compile-time only check. Runtime handles (index_begin >
305 * index_end) correctly, and it can happen in a correct program. If
306 * it is guaranteed to happen, then the range is always empty, which
307 * likely indicates a bug.
308 */
309 if (DXX_CONSTANT_TRUE(!(index_begin < index_end)))
310 DXX_ALWAYS_ERROR_FUNCTION("offset never less than length");
311 #endif
312 #if DXX_HAVE_BUILTIN_OBJECT_SIZE
313 /* Avoid iterator dereference if range is empty */
314 if (index_end)
315 {
316 partial_range_detail::check_range_object_size<typename partial_range_t<iterator_type, index_type>::partial_range_error, required_buffer_size>(file, line, estr, *range_begin, index_begin, index_end);
317 }
318 #endif
319 auto range_end{range_begin};
320 /* Use <= so that (index_begin == 0) makes the expression
321 * always-true, so the compiler will optimize out the test.
322 */
323 if (index_begin <= index_end)
324 {
325 using std::advance;
326 advance(range_begin, index_begin);
327 advance(range_end, index_end);
328 }
329 return {range_begin, range_end};
330 }
331
332 template <
333 #if DXX_HAVE_BUILTIN_OBJECT_SIZE
334 std::size_t required_buffer_size,
335 #endif
336 std::ranges::borrowed_range range_type,
337 typename index_begin_type,
338 typename index_end_type,
339 std::input_or_output_iterator iterator_type = decltype(std::ranges::begin(std::declval<range_type &>()))
340 >
341 [[nodiscard]]
342 dxx_compiler_attribute_always_inline()
343 inline auto (unchecked_partial_range)(
344 #if DXX_HAVE_BUILTIN_OBJECT_SIZE
345 const char *const file, const unsigned line, const char *const estr,
346 #endif
347 range_type &&range, const index_begin_type &index_begin, const index_end_type &index_end)
348 {
349 return unchecked_partial_range_advance<
350 #if DXX_HAVE_BUILTIN_OBJECT_SIZE
351 required_buffer_size,
352 #endif
353 decltype(partial_range_detail::range_index_type<range_type>(nullptr)), iterator_type>(
354 #if DXX_HAVE_BUILTIN_OBJECT_SIZE
355 file, line, estr,
356 #endif
357 std::ranges::begin(std::forward<range_type>(range)),
358 partial_range_detail::cast_index_to_size<range_type, index_begin_type>(index_begin),
359 partial_range_detail::cast_index_to_size<range_type, index_end_type>(index_end)
360 );
361 }
362
363 template <
364 #if DXX_HAVE_BUILTIN_OBJECT_SIZE
365 std::size_t required_buffer_size,
366 #endif
367 /* C arrays (`int a[5];`) can match both the overload that calls
368 * `std::begin(range)` and the overload that calls
369 * `operator*(range)`, leading to an ambiguity. Some supporting
370 * libraries define C arrays, which callers use partial_range on, so
371 * the array use cannot be converted to `std::array`. Use the concept
372 * `std::input_or_output_iterator` to disable this overload in the case of
373 * a C array, since C arrays do not satisfy `std::weakly_incrementable`.
374 *
375 * C++ `std::array` does not permit `operator*(range)`, and so
376 * `std::input_or_output_iterator` disables it by both the dereference
377 * check and the std::weakly_incrementable check.
378 */
379 std::input_or_output_iterator iterator_type
380 >
381 [[nodiscard]]
382 inline auto (unchecked_partial_range)(
383 #if DXX_HAVE_BUILTIN_OBJECT_SIZE
384 const char *const file, const unsigned line, const char *const estr,
385 #endif
386 iterator_type iterator,
387 const std::unsigned_integral auto index_begin, // offset to partial_range must be unsigned
388 const std::unsigned_integral auto index_end // length to partial_range must be unsigned
389 )
390 {
391 /* Do not try to guess an index_type when supplied an iterator. Use
392 * `void` to state that no index_type is available. Callers which
393 * need a defined `index_type` should use the range-based
394 * unchecked_partial_range() instead, which can extract an
395 * index_type from the range_type.
396 */
397 return unchecked_partial_range_advance<
398 #if DXX_HAVE_BUILTIN_OBJECT_SIZE
399 required_buffer_size,
400 #endif
401 void, iterator_type>(
402 #if DXX_HAVE_BUILTIN_OBJECT_SIZE
403 file, line, estr,
404 #endif
405 std::move(iterator), index_begin, index_end
406 );
407 }
408
409 /* Take either a range or an iterator, and forward it to an appropriate
410 * function, adding an index_begin={} along the way.
411 */
412 template <
413 #if DXX_HAVE_BUILTIN_OBJECT_SIZE
414 std::size_t required_buffer_size,
415 #endif
416 typename iterable,
417 typename index_end_type
418 >
419 [[nodiscard]]
420 inline auto (unchecked_partial_range)(
421 #if DXX_HAVE_BUILTIN_OBJECT_SIZE
422 const char *const file, const unsigned line, const char *const estr,
423 #endif
424 iterable &&it, const index_end_type &index_end)
425 {
426 return unchecked_partial_range<
427 #if DXX_HAVE_BUILTIN_OBJECT_SIZE
428 required_buffer_size
429 #endif
430 >(
431 #if DXX_HAVE_BUILTIN_OBJECT_SIZE
432 file, line, estr,
433 #endif
434 std::forward<iterable>(it), index_end_type{}, index_end
435 );
436 }
437
438 template <
439 std::size_t required_buffer_size,
440 std::ranges::borrowed_range range_type,
441 typename index_begin_type,
442 typename index_end_type,
443 typename iterator_type = decltype(std::ranges::begin(std::declval<range_type &&>()))
444 >
445 [[nodiscard]]
446 inline auto (partial_range)(const char *const file, const unsigned line, const char *const estr, range_type &&range, const index_begin_type &index_begin, const index_end_type &index_end)
447 {
448 const auto sz_begin{partial_range_detail::cast_index_to_size<range_type, index_begin_type>(index_begin)};
449 const auto sz_end{partial_range_detail::cast_index_to_size<range_type, index_end_type>(index_end)};
450 partial_range_detail::check_range_bounds<
451 typename partial_range_t<iterator_type, decltype(partial_range_detail::range_index_type<range_type>(nullptr))>::partial_range_error,
452 required_buffer_size
453 >(file, line, estr, reinterpret_cast<uintptr_t>(std::addressof(range)), sz_begin, sz_end, std::size(range));
454 return unchecked_partial_range<
455 #if DXX_HAVE_BUILTIN_OBJECT_SIZE
456 required_buffer_size,
457 #endif
458 range_type>(
459 #if DXX_HAVE_BUILTIN_OBJECT_SIZE
460 file, line, estr,
461 #endif
462 std::forward<range_type>(range), sz_begin, sz_end
463 );
464 }
465
466 template <
467 std::size_t required_buffer_size,
468 std::ranges::borrowed_range range_type,
469 typename index_end_type
470 >
471 [[nodiscard]]
472 inline auto (partial_range)(const char *const file, const unsigned line, const char *const estr, range_type &&range, const index_end_type &index_end)
473 {
474 return partial_range<required_buffer_size, range_type, index_end_type, index_end_type>(file, line, estr, std::forward<range_type>(range), index_end_type{}, index_end);
475 }
476
477 template <
478 std::size_t required_buffer_size,
479 std::ranges::borrowed_range range_type,
480 typename index_begin_type,
481 typename index_end_type
482 >
483 [[nodiscard]]
484 inline auto (partial_const_range)(const char *const file, const unsigned line, const char *const estr, range_type &&range, const index_begin_type &index_begin, const index_end_type &index_end)
485 {
486 return partial_range<required_buffer_size, const range_type, index_begin_type, index_end_type>(file, line, estr, std::forward<const range_type>(range), index_begin, index_end);
487 }
488
489 template <
490 std::size_t required_buffer_size,
491 std::ranges::borrowed_range range_type,
492 typename index_end_type
493 >
494 [[nodiscard]]
495 inline auto (partial_const_range)(const char *const file, const unsigned line, const char *const estr, range_type &&range, const index_end_type &index_end)
496 {
497 return partial_range<required_buffer_size, const range_type, index_end_type>(file, line, estr, std::forward<const range_type>(range), index_end);
498 }
499
500 #if DXX_HAVE_BUILTIN_OBJECT_SIZE
501 /* This macro is conditionally defined, because in the #else case, a
502 * bare invocation supplies all required parameters. In the #else case:
503 * - `required_buffer_size` is not a template parameter
504 * - all other template parameters can be deduced
505 * - the file, line, and string form of the expression are not function
506 * parameters.
507 */
508 #define unchecked_partial_range(T,...) unchecked_partial_range<partial_range_detail::required_buffer_size<sizeof(__FILE__), sizeof(#T)>>(__FILE__, __LINE__, #T, T, ##__VA_ARGS__)
509 #endif
510 #define partial_range(T,...) partial_range<partial_range_detail::required_buffer_size<sizeof(__FILE__), sizeof(#T)>>(__FILE__, __LINE__, #T, T, ##__VA_ARGS__)
511 #define partial_const_range(T,...) partial_const_range<partial_range_detail::required_buffer_size<sizeof(__FILE__), sizeof(#T)>>(__FILE__, __LINE__, #T, T, ##__VA_ARGS__)