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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
use core::fmt::{self, Debug};
use core::mem::{ManuallyDrop, MaybeUninit};

use crate::{
    array::IntoIter,
    drop_flavor::{DropFlavor, MayDrop, NonDrop, as_inner, as_inner_mut, wrap},
};

use typewit::Identity;

/// For constructing an array element by element.
///
/// This type can be constructed with these functions:
/// - [`of_copy`](Self::of_copy): for building an array of `Copy` elements,
///   needed for using `ArrayBuilder` in functions that have early returns.
/// - [`of_assumed_nondrop`](Self::of_assumed_nondrop):
///   for building an array of non-drop elements,
///   needed for using `ArrayBuilder` in functions that have early returns.
/// - [`of_drop`](Self::of_drop):
///   for building an array of any type, useful in functions without early returns.
///
///
/// # Example
///
/// ```rust
/// use konst::array::ArrayBuilder;
///
/// assert_eq!(ARR, [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]);
///
/// const ARR: [u32; 10] = {
///     let mut builder = ArrayBuilder::of_copy();
///     builder.push(1);
///     builder.push(1);
///
///     while !builder.is_full() {
///         let [.., a, b] = *builder.as_slice() else { unreachable!() };
///
///         builder.push(a + b);
///     }
///
///     builder.build()
/// };
/// ```
#[repr(transparent)]
#[cfg_attr(feature = "docsrs", doc(cfg(feature = "iter")))]
pub struct ArrayBuilder<T, const N: usize, D: DropFlavor> {
    inner: D::Wrap<ArrayBuilderInner<T, N>>,
}

#[repr(C)]
pub struct ArrayBuilderInner<T, const N: usize> {
    array: [MaybeUninit<T>; N],
    inited: usize,
}

impl<T, const N: usize> ArrayBuilderInner<T, N> {
    const fn into_builder<D: DropFlavor>(self) -> ArrayBuilder<T, N, D> {
        ArrayBuilder { inner: wrap(self) }
    }
}

impl<T, const N: usize> ArrayBuilder<T, N, MayDrop> {
    /// Constructs an empty ArrayBuilder of an element type that may need dropping,
    /// useful in functions without early returns.
    ///
    /// The `Identity` bound emulates a type equality constraint,
    /// this allows specifying `N` through this constructor,
    /// while infering the other arguments.
    #[inline(always)]
    pub const fn of_drop<const N2: usize>() -> Self
    where
        Self: Identity<Type = ArrayBuilder<T, N2, MayDrop>>,
    {
        Self::of_any()
    }
}

impl<T, const N: usize> ArrayBuilder<T, N, NonDrop> {
    /// Constructs an empty ArrayBuilder of Copy element types,
    /// needed for using `ArrayBuilder` in functions with early returns.
    ///
    /// The `Identity` bound emulates a type equality constraint,
    /// this allows specifying `N` through this constructor,
    /// while infering the other arguments.
    #[inline(always)]
    pub const fn of_copy<const N2: usize>() -> Self
    where
        T: Copy,
        Self: Identity<Type = ArrayBuilder<T, N2, NonDrop>>,
    {
        Self::of_any()
    }

    /// Constructs an empty ArrayBuilder of element types that are assumed to not need dropping,
    /// needed for using `ArrayBuilder` in functions with early returns.
    ///
    /// If the elements *do* need dropping, the builder will leak them
    /// unless `.build()` returns susccessfully.
    ///
    /// The `Identity` bound emulates a type equality constraint,
    /// this allows specifying `N` through this constructor,
    /// while infering the other arguments.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::ops::Range;
    /// use konst::{array, try_opt};
    ///
    ///
    /// const ARR5: [Range<i8>; 5] = make_ranges().unwrap();
    /// assert_eq!(ARR5, [0..0, 1..1, 2..8, 3..27, 4..64]);
    ///
    /// const ARR6: [Range<i8>; 6] = make_ranges().unwrap();
    /// assert_eq!(ARR6, [0..0, 1..1, 2..8, 3..27, 4..64, 5..125]);
    ///
    /// const ARR7: Option<[Range<i8>; 7]> = make_ranges();
    /// assert_eq!(ARR7, None);
    ///
    ///
    /// const fn make_ranges<const N: usize>() -> Option<[Range<i8>; N]> {
    ///     let mut builder = array::ArrayBuilder::of_assumed_nondrop();
    ///     
    ///     while !builder.is_full() {
    ///         let l = builder.len() as i8;
    ///         builder.push(l..try_opt!(l.checked_pow(3)));
    ///     }
    ///     
    ///     Some(builder.build())
    /// }
    ///
    /// ```
    ///
    #[inline(always)]
    pub const fn of_assumed_nondrop<const N2: usize>() -> Self
    where
        Self: Identity<Type = ArrayBuilder<T, N2, NonDrop>>,
    {
        Self::of_any()
    }
}

impl<T, const N: usize, D: DropFlavor> ArrayBuilder<T, N, D> {
    // Constructs an empty ArrayBuilder of any flavor.
    const fn of_any() -> Self {
        ArrayBuilderInner {
            array: crate::maybe_uninit::uninit_array(),
            inited: 0,
        }
        .into_builder()
    }

    /// The amount of initialized elements in the array
    ///
    /// # Example
    ///
    /// ```rust
    /// use konst::array::ArrayBuilder;
    ///
    /// let mut builder = ArrayBuilder::of_copy::<3>();
    ///
    /// assert_eq!(builder.len(), 0);
    ///
    /// builder.push(3);
    /// assert_eq!(builder.len(), 1);
    ///
    /// builder.push(5);
    /// assert_eq!(builder.len(), 2);
    ///
    /// builder.push(8);
    /// assert_eq!(builder.len(), 3);
    /// ```
    ///
    pub const fn len(&self) -> usize {
        as_inner::<D, _>(&self.inner).inited
    }

    /// Whether the array has at least one initialized element.
    ///
    /// # Example
    ///
    /// ```rust
    /// use konst::array::ArrayBuilder;
    ///
    /// let mut builder = ArrayBuilder::of_copy::<3>();
    ///
    /// assert!( builder.is_empty());
    ///
    /// builder.push(3);
    /// assert!(!builder.is_empty());
    ///
    /// builder.push(5);
    /// assert!(!builder.is_empty());
    ///
    /// builder.push(8);
    /// assert!(!builder.is_empty());
    /// ```
    ///
    pub const fn is_empty(&self) -> bool {
        as_inner::<D, _>(&self.inner).inited == 0
    }

    /// Whether the array has been fully initialized
    ///
    /// # Example
    ///
    /// ```rust
    /// use konst::array::ArrayBuilder;
    ///
    /// let mut builder = ArrayBuilder::of_copy::<3>();
    ///
    /// assert!(!builder.is_full());
    ///
    /// builder.push(3);
    /// assert!(!builder.is_full());
    ///
    /// builder.push(5);
    /// assert!(!builder.is_full());
    ///
    /// builder.push(8);
    /// assert!(builder.is_full());
    /// ```
    ///
    pub const fn is_full(&self) -> bool {
        as_inner::<D, _>(&self.inner).inited == N
    }

    /// Gets the initialized part of the array as a slice
    ///
    /// # Example
    ///
    /// ```rust
    /// use konst::array::ArrayBuilder;
    ///
    /// let mut builder = ArrayBuilder::of_copy::<3>();
    ///
    /// assert_eq!(builder.as_slice(), [].as_slice());
    ///
    /// builder.push(3);
    /// assert_eq!(builder.as_slice(), [3].as_slice());
    ///
    /// builder.push(5);
    /// assert_eq!(builder.as_slice(), [3, 5].as_slice());
    ///
    /// builder.push(8);
    /// assert_eq!(builder.as_slice(), [3, 5, 8].as_slice());
    /// ```
    ///
    pub const fn as_slice(&self) -> &[T] {
        // SAFETY: self.array is guaranteed initialized up to this.inited - 1 inclusive
        unsafe {
            let this = as_inner::<D, _>(&self.inner);

            core::slice::from_raw_parts(this.array.as_ptr().cast::<T>(), this.inited)
        }
    }

    /// Gets the initialized part of the array as a mutable slice
    ///
    /// # Example
    ///
    /// ```rust
    /// use konst::array::ArrayBuilder;
    ///
    /// let mut builder = ArrayBuilder::of_copy::<3>();
    ///
    /// assert_eq!(builder.as_mut_slice(), [].as_mut_slice());
    ///
    /// builder.push(3);
    /// assert_eq!(builder.as_mut_slice(), [3].as_mut_slice());
    ///
    /// builder.push(5);
    /// assert_eq!(builder.as_mut_slice(), [3, 5].as_mut_slice());
    ///
    /// builder.push(8);
    /// assert_eq!(builder.as_mut_slice(), [3, 5, 8].as_mut_slice());
    /// ```
    ///
    pub const fn as_mut_slice(&mut self) -> &mut [T] {
        let this = as_inner_mut::<D, _>(&mut self.inner);

        // SAFETY: this.array is guaranteed initialized up to this.inited - 1 inclusive
        unsafe { core::slice::from_raw_parts_mut(this.array.as_mut_ptr().cast::<T>(), this.inited) }
    }

    /// Appends `val` to the array.
    ///
    /// # Panic
    ///
    /// Panics if `self.len() == N`, i.e.: the array is fully initialized.
    ///
    /// # Example
    ///
    /// ```rust
    /// use konst::array::ArrayBuilder;
    ///
    /// let mut builder = ArrayBuilder::of_copy::<3>();
    ///
    /// builder.push(3);
    /// builder.push(5);
    /// builder.push(8);
    ///
    /// assert_eq!(builder.build(), [3, 5, 8]);
    /// ```
    ///
    #[track_caller]
    pub const fn push(&mut self, val: T) {
        let this = as_inner_mut::<D, _>(&mut self.inner);

        assert!(this.inited < N, "trying to add an element to full array");

        this.array[this.inited] = MaybeUninit::new(val);

        this.inited += 1;
    }

    /// Appends `another_array` to the array.
    ///
    /// # Panic
    ///
    /// Panics if `self.len() + N2 > N`
    ///
    /// # Example
    ///
    /// ```rust
    /// use konst::array::ArrayBuilder;
    ///
    /// let mut builder = ArrayBuilder::of_copy::<3>();
    ///
    /// builder.extend_from_array([3, 5, 8]);
    ///
    /// assert_eq!(builder.build(), [3, 5, 8]);
    /// ```
    ///
    #[track_caller]
    pub const fn extend_from_array<const N2: usize>(&mut self, another_array: [T; N2]) {
        let this = as_inner_mut::<D, _>(&mut self.inner);

        let next_len = match this.inited.checked_add(N2) {
            Some(x) if x <= N => x,
            _ => panic!("trying to add too many elements to array"),
        };

        unsafe {
            this.array
                .as_mut_ptr()
                .add(this.inited)
                .cast::<[T; N2]>()
                .write(another_array);
        }

        this.inited = next_len;
    }

    /// Appends copies of all the elements in `slice` to the array.
    ///
    /// # Panic
    ///
    /// Panics if `self.len() + N2 > N`
    ///
    /// # Example
    ///
    /// ```rust
    /// use konst::array::ArrayBuilder;
    ///
    /// let mut builder = ArrayBuilder::of_copy::<3>();
    ///
    /// builder.extend_from_slice(&[3, 5, 8]);
    ///
    /// assert_eq!(builder.build(), [3, 5, 8]);
    /// ```
    ///
    #[track_caller]
    pub const fn extend_from_slice(&mut self, slice: &[T])
    where
        T: Copy,
    {
        let this = as_inner_mut::<D, _>(&mut self.inner);

        let next_len = match this.inited.checked_add(slice.len()) {
            Some(x) if x <= N => x,
            _ => panic!("trying to add too many elements to array"),
        };

        unsafe {
            this.array
                .as_mut_ptr()
                .cast::<T>()
                .add(this.inited)
                .copy_from_nonoverlapping(slice.as_ptr(), slice.len())
        }

        this.inited = next_len;
    }

    /// Unwraps this ArrayBuilder into an array.
    ///
    /// # Panic
    ///
    /// Panics if `self.len() != N`, i.e.: the array is not fully initialized.
    ///
    /// # Example
    ///
    /// ```rust
    /// use konst::array::ArrayBuilder;
    ///
    /// assert_eq!(ARR, [3, 5, 8]);
    ///
    /// const ARR: [u8; 3] = {
    ///     let mut builder = ArrayBuilder::of_copy();
    ///     
    ///     builder.push(3);
    ///     builder.push(5);
    ///     builder.push(8);
    ///
    ///     builder.build()
    /// };
    /// ```
    ///
    #[track_caller]
    pub const fn build(self) -> [T; N] {
        assert!(
            self.is_full(),
            "trying to unwrap a non-fully-initialized array"
        );

        // SAFETY: self.array is guaranteed fully initialized by the fact that
        //         each element is inited in lockstep with incrementing self.inited by 1,
        //         and the assertion above.
        unsafe {
            let mut this = ManuallyDrop::new(self);

            // this cast is guaranteed correct because
            // `[MaybeUninit<T>; N]` is at offset 0
            (&raw mut this).cast::<[T; N]>().read()
        }
    }

    /// Gets a bitwise copy of this Builder, requires `T: Copy`.
    pub const fn copy(&self) -> Self
    where
        T: Copy,
    {
        ArrayBuilderInner {
            ..*as_inner::<D, _>(&self.inner)
        }
        .into_builder()
    }

    /// Converts this `ArrayBuilder` to have a `MayDrop` drop flavor.
    pub const fn into_drop(self) -> ArrayBuilder<T, N, MayDrop> {
        self.into_any_flavor()
    }

    /// Converts this `ArrayBuilder` to have a `NonDrop` drop flavor
    /// by requiring that `T` is `Copy`.
    pub const fn into_copy(self) -> ArrayBuilder<T, N, NonDrop>
    where
        T: Copy,
    {
        self.into_any_flavor()
    }

    /// Converts this `ArrayBuilder` to have any flavor.
    const fn into_any_flavor<D2: DropFlavor>(self) -> ArrayBuilder<T, N, D2> {
        // SAFETY: changing the D type parameter does not change the layout of the type
        unsafe { crate::__priv_transmute!(ArrayBuilder<T, N, D>, ArrayBuilder<T, N, D2>, self) }
    }

    /// Helper for inferring the length of the built array from an [`IntoIter`].
    pub const fn infer_length_from_consumer<U, D2>(&self, _consumer: &IntoIter<U, N, D2>)
    where
        D2: DropFlavor,
    {
    }
}

impl<T, const N: usize> Default for ArrayBuilder<T, N, MayDrop> {
    fn default() -> Self {
        Self::of_drop()
    }
}

impl<T: Copy, const N: usize> Default for ArrayBuilder<T, N, NonDrop> {
    fn default() -> Self {
        Self::of_copy()
    }
}

impl<T: Debug, const N: usize, D: DropFlavor> Debug for ArrayBuilder<T, N, D> {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        let this = as_inner::<D, _>(&self.inner);

        fmt.debug_struct("ArrayBuilder")
            .field("array", &self.as_slice())
            .field("uninit_len", &(N - this.inited))
            .finish()
    }
}

impl<T: Clone, const N: usize, D: DropFlavor> Clone for ArrayBuilder<T, N, D> {
    fn clone(&self) -> Self {
        let mut this = Self::of_any();
        for elem in self.as_slice() {
            this.push(elem.clone());
        }
        this
    }
}

impl<T, const N: usize> Drop for ArrayBuilderInner<T, N> {
    fn drop(&mut self) {
        unsafe {
            let inited = self.inited;

            let ptr = self.array.as_mut_ptr().cast::<T>();

            core::ptr::slice_from_raw_parts_mut(ptr, inited).drop_in_place();
        }
    }
}