konst 0.4.3

Const equivalents of std features: comparison, destructuring, iteration, and parsing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
#![expect(clippy::empty_loop)]

#[doc(hidden)]
#[inline(always)]
pub const fn split_array_ptr_len<T, U, const N: usize>(
    ptr: *mut U,
    _phantom: core::marker::PhantomData<fn([T; N]) -> [T; N]>,
) -> (*mut T, usize) {
    (ptr.cast(), N)
}

#[doc(hidden)]
#[inline(always)]
pub const fn fake_read_array_ref<T, const N: usize>(_ptr: &[T; N]) -> [T; N] {
    loop {}
}

//////

/// Nested destructuring of structs/tuples/arrays (composite types).
///
/// Use this macro over [`destructure`] if you need to destructure composite types
/// into *nested* fields that may need dropping.
///
/// [**for examples look here**](#examples)
///
/// # Motivation
///
/// This macro works around a limitation of Rust as of 1.91,
/// where in a const context, a non-`Drop` type can't be destructured into its elements/fields
/// if any of them is `Drop`.
///
/// Even simple cases like this don't compile:
///
/// ```rust,compile_fail
/// const fn foo<T>(((a, b), c): ((T, T), T)) -> [T; 3] {
///     [a, b, c]
/// }
/// ```
///
/// ```text
/// error[E0493]: destructor of `((T, T), T)` cannot be evaluated at compile-time
///  --> src/lib.rs:1:17
///   |
/// 1 | const fn foo<T>(((a, b), c): ((T, T), T)) -> [T; 3] {
///   |                 ^^^^^^^^^^^ the destructor for this type cannot be evaluated in constant functions
/// 2 |     [a, b, c]
/// 3 | }
///   | - value is dropped here
/// ```
///
/// # Requirements/Limitations
///
/// This macro has these requirements and limitations:
/// - it only supports `..` patterns in tuples or structs
///   when the `#[forget_ignored_fields]` attribute is used,
///   which forgets unmentioned fields.
///   (arrays always support the `..` pattern, dropping unmentioned elements)
/// - it requires that passed-in structs do not impl `Drop`
///   (like built-in destructuring does).
/// - it always moves the expression on the right-hand-side,
///   even if the pattern doesn't require it.
///
/// # Syntax
///
/// This section describes the syntax allowed by `destructure_rec` using
/// `macro_rules!` syntax with pseudo-metavariable types,
/// the allowed syntax is
/// ```text
/// $(#[forget_ignored_fields])?
/// $pattern:dr_pat $( : $type:ty )? = $val:expr
/// ```
///
/// `dr_pat` can be any of:
/// - `_ $( @ $nested_pat:dr_pat )?`
/// - `$(ref)? $(mut)? $ident:ident $( @ $nested_pat:dr_pat )?`
/// - `& $(mut)? $pat:pat`
/// - `$typename:path`
/// - `$typename:path { $($field_name:ident : $field_pat:dr_pat),* $(, ..)? $(,)? }`
/// - `$typename:path ( $($field_pat:dr_pat),* $(, ..)? $(,)? )`
/// - `[ $($pref_elem:dr_pat),* $(, $($ident:ident @)? ..)? $(, $suff_elem:dr_pat)* $(,)? ]`
/// - `( $($pref_elem:dr_pat),* $(, ..)?  $(,)? )`
///
/// The `#[forget_ignored_fields]` attribute turns the macro from forbidding
/// tuple and struct patterns that use a trailing `..` to allowing
/// the pattern, and to cause unmentioned fields to *not* be dropped.
///
/// # Examples
///
/// The functions in these examples demonstrate destructuring non-Copy types in const,
/// which can't be done with built-in destructuring as of Rust 1.91.
///
/// ### Braced Struct
///
/// ```rust
/// use std::ops::Range;
///
/// assert_eq!(TUP, (3, 5, 8, 13));
///
/// const TUP: (u32, u32, u32, u32) = ranges_to_tuple([3..5, 8..13]);
///
/// const fn ranges_to_tuple<T>(ranges: [Range<T>; 2]) -> (T, T, T, T) {
///     konst::destructure_rec!{
///         [Range { start: a, end: b }, Range { start: c, end: d }] = ranges
///     }
///
///     (a, b, c, d)
/// }
/// ```
///
/// ### Flatten
///
/// ```rust
/// assert_eq!(FLAT, [3, 5, 8, 13]);
///
/// const FLAT: [u32; 4] = flatten([[3, 5], [8, 13]]);
///
/// const fn flatten<T>(array: [[T; 2]; 2]) -> [T; 4] {
///     konst::destructure_rec!{[[a, b], [c, d]] = array}
///     
///     [a, b, c, d]
/// }
/// ```
///
/// [`destructure`]: crate::destructure
#[macro_export]
#[cfg_attr(feature = "docsrs", doc(cfg(feature = "konst_proc_macros")))]
macro_rules! destructure_rec {
    ($($tt:tt)*) => (
        $crate::__::__destructure__unwrap_pats!{$crate () $($tt)*}
    );
}

#[doc(hidden)]
#[macro_export]
macro_rules! __destructure_rec__inner {
    (
        $(#[forget_ignored_fields $(@$forget_ignored_fields:tt)?])?
        {$patterns:tt}
        $(: $type:ty )?
        = $expr:expr $(;)?
    ) => (
        let mut val $(: $crate::__::ManuallyDrop<$type>)? = $crate::__::ManuallyDrop::new($expr);

        let ptr: *mut _ = $crate::macros::destructuring::cast_manuallydrop_ptr(&raw mut val);

        $crate::__destructure_rec__recursive! {
            [
                $(#[forget_ignored_fields $(@$forget_ignored_fields)?])?
            ]
            [
                $(#[forget_ignored_fields $(@$forget_ignored_fields)?])?
            ]

            {ptr}

            $patterns
        }
    );
}

#[doc(hidden)]
#[macro_export]
macro_rules! __destructure_rec__recursive {
    (
        $fixed:tt $fixed2:tt {$ptr:expr}
        ( $pattern:tt binding )
    ) => {
        // SAFETY:
        // ptr is a valid pointer to the type that is read out,
        // the pointee comes from a ManuallyDrop,
        // and it's only read out once.
        //
        // uses `read_unaligned` because this might be a pointer into a packed struct
        let $pattern = unsafe { <*mut _>::read_unaligned($ptr) };
    };

    (
        $fixed:tt [] $ptr:tt
        ( $pattern:tt struct $path:tt $fields:tt ($($dotdot:tt)*) )
    ) => {
        $crate::__::compile_error!{
            "`..` patterns are not supported in struct patterns by default,\
             because they can forget fields\
            "
        }
    };

    (
        $fixed:tt
        [ $(#[forget_ignored_fields])? ]
        {$ptr:expr}

        (
            $pattern:tt
            struct
            ($path:path)
            {$($field_name:tt $field_pat:tt,)*}
            $(($($dotdot:tt)*))?
        )
    ) => {
        let ptr = $ptr;

        // assert that `*ptr` is a struct, not a reference to a struct,
        // and that it has all the fields the user listed.
        #[allow(unreachable_code)]
        if false {
            loop {}

            let expected @ $path {$($field_name: _,)* $($($dotdot)*)?};

            // SAFETY: dead code
            let read_out = unsafe {
                // uses `read_unaligned` because this might be a pointer into a packed struct
                <*mut _>::read_unaligned(ptr)
            };

            $crate::macros::destructuring::assert_same_type(expected, read_out);

            _ = ||{
                use $crate::macros::destructuring::__GetImplsHelper as _;

                // assert that the struct doesn't impl Drop
                // (its fields can, just not the struct itself)
                let _assertion_expected: $crate::macros::destructuring::__DoesNotImplDrop<_> =
                    if false {
                        $crate::macros::destructuring::__DoesNotImplDrop::new(ptr)
                    } else {
                        let assertion = $crate::macros
                            ::destructuring
                            ::__GetImpls_IWRHQLPNNIEU8C6W(
                                $crate::macros::destructuring::make_phantom(ptr)
                            ).__impls_drop_iwrhqlpnnieu8c6w();

                        assertion
                    };
            };
        }

        $(
            $crate::__destructure_rec__recursive! {
                $fixed
                $fixed
                {
                    // SAFETY: ptr is a pointer to a struct with the `$field_name` field
                    unsafe { &raw mut (*ptr).$field_name }
                }
                $field_pat
            }
        )*
    };

    (
        $fixed:tt [] $ptr:tt
        ( $pattern:tt tuple $fields:tt $dotdot:tt ())
    ) => {
        $crate::__::compile_error!{
            "`..` patterns are not supported in tuple patterns by default,\
             because they can forget fields\
            "
        }
    };

    (
        $fixed:tt [] $ptr:tt
        ( $pattern:tt tuple $fields:tt $dotdot:tt $suffix_fields:tt)
    ) => {
        $crate::__::compile_error!{
            "tuple patterns do not support `..` with trailing fields"
        }
    };

    (
        $fixed:tt
        [ $(#[forget_ignored_fields])? ]
        {$ptr:expr}

        (
            $pattern:tt
            tuple
            ($($field:tt $field_pat:tt,)*)
            $(
                ($($dotdot:tt)*)
                ($($suffix_fields:tt)*)
            )?
        )
    ) => {
        let ptr = $ptr;

        // assert that `*ptr` is a tuple, not a reference to a tuple
        #[allow(unreachable_code)]
        if false {
            loop {}

            let expected @ (
                $($crate::__first_pat!(_, $field),)*
                $($crate::__first_pat!(_, $($dotdot)*),)?
            );

            // SAFETY: dead code
            let read_out = unsafe {
                // uses `read_unaligned` because this might be a pointer into a packed struct
                <*mut _>::read_unaligned(ptr)
            };

            $crate::macros::destructuring::assert_same_type(expected, read_out)
        }

        $(
            $crate::__destructure_rec__recursive! {
                $fixed
                $fixed
                {
                    // SAFETY: ptr is a pointer to a tuple with the `$field` field
                    unsafe { &raw mut (*ptr).$field }
                }
                $field_pat
            }
        )*
    };

    (
        $fixed:tt
        $fixed2:tt
        {$ptr:expr}

        (
            $pattern:tt
            array
            ($($pre_index:tt $pre_pat:tt,)*)
            $(
                ($rem_index:tt $($rem_pat:tt)*)
                ($($post_index:tt $post_pat:tt,)*)
            )?
        )
    ) => {
        let ptr = $ptr;

        let arr_type_len_phantom = $crate::__::PhantomData;
        $(  let $crate::__first_pat!(rem_ty_phantom, $($rem_pat)*) = $crate::__::PhantomData; )?

        // asserts the length of the array,
        // and computes the length of the array produced by `@ ..` patterns
        #[allow(unreachable_code)]
        if false {
            loop {}

            let [
                $($crate::__first_pat!(_, $pre_pat),)*
                $(
                    rem @ ..,
                    $($crate::__first_pat!(_, $post_pat),)*
                )?
            ] = unsafe {
                // SAFETY: unreachable code

                // assert that `*ptr` is an array, not a reference to an array
                arr_type_len_phantom = $crate::macros::destructuring::array_into_phantom({
                    // uses `read_unaligned` because this might be a pointer into a packed struct
                    let array = <*mut _>::read_unaligned(ptr);
                    array
                });

                $crate::macros::destructuring_rec::fake_read_array_ref(&*ptr)
            };

            $(
                rem_ty_phantom = $crate::macros::destructuring::array_into_phantom(
                    $crate::__first_expr!(rem, $rem_index)
                );
            )?

        }

        let (ptr_elem, len) = $crate::macros::destructuring_rec::split_array_ptr_len(
            ptr,
            arr_type_len_phantom,
        );

        $(
            $crate::__destructure_rec__recursive! {
                $fixed $fixed
                {
                    // SAFETY:
                    // `ptr_elem` is a pointer into the start of an array of `len` elements.
                    // `$pre_index` is in-bounds for the array
                    unsafe { <*mut _>::add(ptr_elem, $pre_index) }
                }
                $pre_pat
            }
        )*

        $(

            // SAFETY:
            // the array being wrapped in a ManuallyDrop,
            // and the assertions above, ensure that this read is safe.
            let $($rem_pat)* = unsafe {
                let rem_ptr = $crate::macros::destructuring::cast_ptr_with_phantom(
                    <*mut _>::add(ptr_elem, $rem_index),
                    rem_ty_phantom,
                );

                // uses `read_unaligned` because this might be a pointer into a packed struct
                <*mut _>::read_unaligned(rem_ptr)
            };

            $(
                $crate::__destructure_rec__recursive! {
                    $fixed $fixed
                    {
                        // SAFETY:
                        // `ptr_elem` is a pointer into the start of an array of `len` elements.
                        //
                        // `len.wrapping_sub($post_index)` doesn't overflow because
                        // the `__destructure__unwrap_pats` macro passes in-bounds indices,
                        // and the `if false` above asserts the length of the array.
                        unsafe { <*mut _>::add(ptr_elem, len.wrapping_sub($post_index)) }
                    }
                    $post_pat
                }
            )*
        )?
    };
}