placid 0.2.1

Separated ownership and in-place construction in Rust
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
use core::{
    clone::TrivialClone,
    convert::Infallible,
    marker::PhantomData,
    mem::{self, MaybeUninit},
    ptr,
};

use crate::{
    init::{Init, InitError, InitPin, InitPinResult, InitResult, Initializer, IntoInitPin},
    owned::Own,
    pin::DropSlot,
    uninit::Uninit,
};

#[inline]
fn maybe_uninit_slice<T, const N: usize>(m: &mut MaybeUninit<[T; N]>) -> &mut [MaybeUninit<T>] {
    unsafe { &mut *(m.as_mut_ptr() as *mut [MaybeUninit<T>; N]) }
}

/// Error type for slice initialization failures.
///
/// This structure is returned from slice initializers when the source and
/// target slices have mismatched lengths.
#[derive(Debug, thiserror::Error, Clone, Copy, PartialEq)]
#[error("slice length mismatch")]
pub struct SliceError;

trait SpecInitSlice<T> {
    fn init_slice(self, place: Uninit<'_, [T]>) -> InitResult<'_, [T], SliceError>;

    fn init_array<const N: usize>(
        self,
        place: Uninit<'_, [T; N]>,
    ) -> InitResult<'_, [T; N], SliceError>;
}

impl<T: Clone> SpecInitSlice<T> for &[T] {
    default fn init_slice(self, mut place: Uninit<'_, [T]>) -> InitResult<'_, [T], SliceError> {
        if place.len() != self.len() {
            return Err(InitError { error: SliceError, place });
        }

        place.write_clone_of_slice(self);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init() })
    }

    default fn init_array<const N: usize>(
        self,
        mut place: Uninit<'_, [T; N]>,
    ) -> InitResult<'_, [T; N], SliceError> {
        if N != self.len() {
            return Err(InitError { error: SliceError, place });
        }

        maybe_uninit_slice(&mut place).write_clone_of_slice(self);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init() })
    }
}

impl<T: TrivialClone> SpecInitSlice<T> for &[T] {
    fn init_slice(self, mut place: Uninit<'_, [T]>) -> InitResult<'_, [T], SliceError> {
        if place.len() != self.len() {
            return Err(InitError { error: SliceError, place });
        }

        // SAFETY: `TrivialClone` guarantees that we can copy the bits directly.
        unsafe { ptr::copy_nonoverlapping(self.as_ptr(), place.as_mut_ptr().cast(), self.len()) };
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init() })
    }

    fn init_array<const N: usize>(
        self,
        mut place: Uninit<'_, [T; N]>,
    ) -> InitResult<'_, [T; N], SliceError> {
        if N != self.len() {
            return Err(InitError { error: SliceError, place });
        }

        // SAFETY: `TrivialClone` guarantees that we can copy the bits directly.
        unsafe { ptr::copy_nonoverlapping(self.as_ptr(), place.as_mut_ptr().cast(), self.len()) };
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init() })
    }
}

/// Initializes a slice by copying or cloning elements from a source slice.
///
/// This initializer is created by the [`slice()`] factory function or through
/// the [`IntoInitPin`] trait for slice types.
#[derive(Debug, PartialEq)]
pub struct Slice<'a, T>(&'a [T]);

impl<T> Initializer for Slice<'_, T> {
    type Error = SliceError;
}

impl<T: Clone> InitPin<[T]> for Slice<'_, T> {
    #[inline]
    fn init_pin<'a, 'b>(
        self,
        place: Uninit<'a, [T]>,
        slot: DropSlot<'a, 'b, [T]>,
    ) -> InitPinResult<'a, 'b, [T], SliceError> {
        match self.0.init_slice(place) {
            Ok(own) => Ok(Own::into_pin(own, slot)),
            Err(err) => Err(err.into_pin(slot)),
        }
    }
}

impl<T: Clone> Init<[T]> for Slice<'_, T> {
    #[inline]
    fn init(self, place: Uninit<'_, [T]>) -> InitResult<'_, [T], SliceError> {
        self.0.init_slice(place)
    }
}

impl<T: Clone, const N: usize> InitPin<[T; N]> for Slice<'_, T> {
    #[inline]
    fn init_pin<'a, 'b>(
        self,
        place: Uninit<'a, [T; N]>,
        slot: DropSlot<'a, 'b, [T; N]>,
    ) -> InitPinResult<'a, 'b, [T; N], SliceError> {
        match self.0.init_array(place) {
            Ok(own) => Ok(Own::into_pin(own, slot)),
            Err(err) => Err(err.into_pin(slot)),
        }
    }
}

impl<T: Clone, const N: usize> Init<[T; N]> for Slice<'_, T> {
    #[inline]
    fn init(self, place: Uninit<'_, [T; N]>) -> InitResult<'_, [T; N], SliceError> {
        self.0.init_array(place)
    }
}

/// Initializes a slice by copying or cloning elements from a source slice.
///
/// This is used to initialize a pre-allocated slice by copying (for `Copy`
/// types) or cloning (for `Clone` types) elements from another slice. The
/// source and target slices must have the same length, or the initialization
/// will fail with a [`SliceError`].
///
/// This function is rarely used for direct initialization. Instead, use an
/// `&[T]` slice directly where an initializer is expected, as `&[T]` can be
/// used directly as an initializer. Use this function for combining with other
/// initializers when needed.
///
/// # Examples
///
/// ```rust
/// use placid::prelude::*;
///
/// // Initialize a slice with integers
/// let source = [1, 2, 3, 4, 5];
/// let mut uninit = uninit!([i32; 5]);
/// let owned = uninit.write(&source[..]);
/// assert_eq!(&*owned, &[1, 2, 3, 4, 5]);
/// ```
///
/// Error on length mismatch:
/// ```rust
/// use placid::prelude::*;
///
/// let source = [1, 2, 3];
/// let mut uninit = uninit!([i32; 5]); // Different size
/// let result = uninit.try_write(&source[..]);
/// assert!(result.is_err()); // Fails because lengths don't match
/// ```
#[inline]
pub const fn slice<T: Clone>(s: &[T]) -> Slice<'_, T> {
    Slice(s)
}

impl<'a, T: Clone> IntoInitPin<[T], Slice<'a, T>> for &'a [T] {
    type Init = Slice<'a, T>;
    type Error = SliceError;

    #[inline]
    fn into_init(self) -> Self::Init {
        Slice(self)
    }
}

impl<'a, T: Clone, const N: usize> IntoInitPin<[T; N], Slice<'a, T>> for &'a [T] {
    type Init = Slice<'a, T>;
    type Error = SliceError;

    #[inline]
    fn into_init(self) -> Self::Init {
        Slice(self)
    }
}

/// Initializes a `str` slice by copying from a source string slice.
///
/// This initializer is created by the [`str()`] factory function.
#[derive(Debug, PartialEq)]
pub struct Str<'a>(&'a str);

impl Initializer for Str<'_> {
    type Error = SliceError;
}

impl InitPin<str> for Str<'_> {
    fn init_pin<'a, 'b>(
        self,
        mut place: Uninit<'a, str>,
        slot: DropSlot<'a, 'b, str>,
    ) -> InitPinResult<'a, 'b, str, SliceError> {
        if place.len() != self.0.len() {
            return Err(InitError { error: SliceError, place }.into_pin(slot));
        }

        let src = unsafe { mem::transmute::<&[u8], &[MaybeUninit<u8>]>(self.0.as_bytes()) };
        place.copy_from_slice(src);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init_pin(slot) })
    }
}

impl Init<str> for Str<'_> {
    fn init(self, mut place: Uninit<'_, str>) -> InitResult<'_, str, SliceError> {
        if place.len() != self.0.len() {
            return Err(InitError { error: SliceError, place });
        }

        let src = unsafe { mem::transmute::<&[u8], &[MaybeUninit<u8>]>(self.0.as_bytes()) };
        place.copy_from_slice(src);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init() })
    }
}

/// Initializes a `str` slice by copying from a source string slice.
///
/// This is used to initialize a pre-allocated `str` slice by copying the
/// contents from another string slice. The source and target slices must have
/// the same length, or the initialization will fail with a [`SliceError`].
///
/// Users typically do not need to call this function directly, as `&str` can be
/// used directly as an initializer. Use this function when combining with other
/// initializers.
///
/// # Examples
///
/// ```rust
/// use placid::prelude::*;
///
/// let source = "Hello, world!";
/// let mut uninit: Uninit<str> = uninit!([u8; 13]); // Pre-allocated for 13 bytes
/// let owned = uninit.write(source);
/// assert_eq!(&*owned, "Hello, world!");
/// ```
#[inline]
pub const fn str(s: &str) -> Str<'_> {
    Str(s)
}

impl<'b> IntoInitPin<str, Str<'b>> for &'b str {
    type Init = Str<'b>;
    type Error = SliceError;

    #[inline]
    fn into_init(self) -> Self::Init {
        Str(self)
    }
}

/// Initializes all elements of a slice with a single repeated value.
///
/// This initializer is created by the [`repeat()`] factory function.
#[derive(Debug, PartialEq)]
pub struct Repeat<T>(T);

impl<T> Initializer for Repeat<T> {
    type Error = Infallible;
}

impl<T: Clone> InitPin<[T]> for Repeat<T> {
    fn init_pin<'a, 'b>(
        self,
        mut place: Uninit<'a, [T]>,
        slot: DropSlot<'a, 'b, [T]>,
    ) -> InitPinResult<'a, 'b, [T], Infallible> {
        place.write_filled(self.0);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init_pin(slot) })
    }
}

impl<T: Clone> Init<[T]> for Repeat<T> {
    fn init(self, mut place: Uninit<'_, [T]>) -> InitResult<'_, [T], Infallible> {
        place.write_filled(self.0);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init() })
    }
}

impl<T: Clone, const N: usize> InitPin<[T; N]> for Repeat<T> {
    fn init_pin<'a, 'b>(
        self,
        mut place: Uninit<'a, [T; N]>,
        slot: DropSlot<'a, 'b, [T; N]>,
    ) -> InitPinResult<'a, 'b, [T; N], Infallible> {
        maybe_uninit_slice(&mut place).write_filled(self.0);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init_pin(slot) })
    }
}

impl<T: Clone, const N: usize> Init<[T; N]> for Repeat<T> {
    fn init(self, mut place: Uninit<'_, [T; N]>) -> InitResult<'_, [T; N], Infallible> {
        maybe_uninit_slice(&mut place).write_filled(self.0);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init() })
    }
}

/// Initializes all elements of a slice with a single repeated value.
///
/// This is used to initialize a slice where all elements are the same
/// value. The value is cloned for each position in the slice.
///
/// # Examples
///
/// Filling an array with a repeated value:
///
/// ```rust
/// use placid::prelude::*;
///
/// let place = uninit!([i32; 3]);
/// let owned = place.write(init::repeat(5));
/// assert_eq!(*owned, [5, 5, 5]);
/// ```
#[inline]
pub const fn repeat<T: Clone>(value: T) -> Repeat<T> {
    Repeat(value)
}

/// Initializes a slice by calling a closure for each element.
///
/// This initializer is created by the [`repeat_with()`] factory function.
#[derive(Debug, PartialEq)]
pub struct RepeatWith<F>(F);

impl<F> Initializer for RepeatWith<F> {
    type Error = Infallible;
}

impl<T, F> InitPin<[T]> for RepeatWith<F>
where
    F: Fn(usize) -> T,
{
    fn init_pin<'a, 'b>(
        self,
        mut place: Uninit<'a, [T]>,
        slot: DropSlot<'a, 'b, [T]>,
    ) -> InitPinResult<'a, 'b, [T], Infallible> {
        place.write_with(self.0);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init_pin(slot) })
    }
}

impl<T, F> Init<[T]> for RepeatWith<F>
where
    F: Fn(usize) -> T,
{
    fn init(self, mut place: Uninit<'_, [T]>) -> InitResult<'_, [T], Infallible> {
        place.write_with(self.0);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init() })
    }
}

impl<T, F, const N: usize> InitPin<[T; N]> for RepeatWith<F>
where
    F: Fn(usize) -> T,
{
    fn init_pin<'a, 'b>(
        self,
        mut place: Uninit<'a, [T; N]>,
        slot: DropSlot<'a, 'b, [T; N]>,
    ) -> InitPinResult<'a, 'b, [T; N], Infallible> {
        maybe_uninit_slice(&mut place).write_with(self.0);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init_pin(slot) })
    }
}

impl<T, F, const N: usize> Init<[T; N]> for RepeatWith<F>
where
    F: Fn(usize) -> T,
{
    fn init(self, mut place: Uninit<'_, [T; N]>) -> InitResult<'_, [T; N], Infallible> {
        maybe_uninit_slice(&mut place).write_with(self.0);
        // SAFETY: The place is now initialized.
        Ok(unsafe { place.assume_init() })
    }
}

/// Initializes a slice by calling a closure for each element.
///
/// `RepeatWith` allows you to initialize a slice where each element is produced
/// by calling a closure with the element's index. This provides a flexible way
/// to create complex slice initializations.
///
/// # Examples
///
/// Creating an array of indices:
/// ```rust
/// use placid::prelude::*;
///
/// let mut uninit = uninit!([usize; 5]);
/// let owned = uninit.write(init::repeat_with(|i| i * 2));
/// assert_eq!(&*owned, &[0, 2, 4, 6, 8]);
/// ```
#[inline]
pub const fn repeat_with<T, F>(f: F) -> RepeatWith<F>
where
    F: Fn(usize) -> T,
{
    RepeatWith(f)
}

/// Initializes a slice by consuming an iterator.
///
/// This initializer is created by the [`from_iter()`] factory function.
#[derive(Debug, PartialEq)]
pub struct FromIter<I, T>(I, PhantomData<fn() -> T>);

/// The error type for `FromIter` initialization failures.
#[derive(Debug, thiserror::Error)]
#[error("iterator initialization failed")]
pub struct FromIterError(());

impl<I, T> Initializer for FromIter<I, T> {
    type Error = FromIterError;
}

#[inline]
fn collect_iter_slice<T, I>(uninit: &mut [MaybeUninit<T>], iter: I) -> Result<(), FromIterError>
where
    I: IntoIterator<Item = T>,
{
    let (_, remaining) = uninit.write_iter(iter);
    match remaining.len() {
        0 => Ok(()),
        len => {
            let init_len = uninit.len() - len;
            // SAFETY: We have initialized the first `init_len` elements, so we can safely
            // drop them.
            unsafe { uninit[..init_len].assume_init_drop() };
            Err(FromIterError(()))
        }
    }
}

#[inline]
fn collect_iter_array<T, const N: usize>(
    uninit: &mut MaybeUninit<[T; N]>,
    iter: impl IntoIterator<Item = T>,
) -> Result<(), FromIterError> {
    collect_iter_slice(maybe_uninit_slice(uninit), iter)
}

fn concat_str<'a, I>(uninit: &mut [MaybeUninit<u8>], iter: I) -> Result<(), FromIterError>
where
    I: IntoIterator<Item = &'a str>,
{
    let mut remaining = uninit.len();
    let mut dst = uninit.as_mut_ptr().cast::<u8>();

    for s in iter {
        let bytes = s.as_bytes();
        let len = remaining.min(bytes.len());

        // Checks if `len` is a valid code point boundary.
        if !s.is_char_boundary(len) {
            return Err(FromIterError(()));
        }

        unsafe { ptr::copy_nonoverlapping(bytes.as_ptr(), dst, len) };
        dst = unsafe { dst.add(len) };
        remaining -= len;

        if remaining == 0 {
            return Ok(());
        }
    }

    Err(FromIterError(()))
}

fn collect_chars<I>(uninit: &mut [MaybeUninit<u8>], iter: I) -> Result<(), FromIterError>
where
    I: IntoIterator<Item = char>,
{
    let mut remaining = uninit.len();
    let mut dst = uninit.as_mut_ptr().cast::<u8>();

    for c in iter {
        if remaining < c.len_utf8() {
            return Err(FromIterError(()));
        }

        let mut buf = [0; 4];
        let bytes = c.encode_utf8(&mut buf).as_bytes();

        unsafe { ptr::copy_nonoverlapping(bytes.as_ptr(), dst, bytes.len()) };
        dst = unsafe { dst.add(bytes.len()) };
        remaining -= bytes.len();

        if remaining == 0 {
            return Ok(());
        }
    }

    Err(FromIterError(()))
}

macro_rules! derive_from_iter {
    ($($(@[$($g:tt)*]:)? $item:ty => $ty:ty = $imp:ident),* $(,)?) => {$(
        impl<$($($g)*,)? __I> InitPin<$ty> for FromIter<__I, $item>
        where
            __I: IntoIterator<Item = $item>,
        {
            fn init_pin<'a, 'b>(
                self,
                mut place: Uninit<'a, $ty>,
                slot: DropSlot<'a, 'b, $ty>,
            ) -> InitPinResult<'a, 'b, $ty, FromIterError> {
                match $imp(&mut *place, self.0) {
                    Ok(()) => Ok(unsafe { place.assume_init_pin(slot) }),
                    Err(err) => Err(InitError { error: err, place }.into_pin(slot)),
                }
            }
        }

        impl<$($($g)*,)? __I> Init<$ty> for FromIter<__I, $item>
        where
            __I: IntoIterator<Item = $item>,
        {
            fn init(self, mut place: Uninit<'_, $ty>) -> InitResult<'_, $ty, FromIterError> {
                match $imp(&mut *place, self.0) {
                    Ok(()) => Ok(unsafe { place.assume_init() }),
                    Err(err) => Err(InitError { error: err, place }),
                }
            }
        }
    )*};
}

derive_from_iter! {
    @[T]:                 T => [T]    = collect_iter_slice,
    @[T, const N: usize]: T => [T; N] = collect_iter_array,

    @['t]: &'t str => str = concat_str,
              char => str = collect_chars,
}

/// Initializes a slice/str by collecting an iterator.
///
/// Unlike [`Extend`] and [`Iterator::collect_into`], which don't require all
/// the spare capacity to be filled, this initializer requires the iterator to
/// produce items enough to fill the entire target place. This behavior is
/// consistent with other slice initializers such as [`repeat`].
///
/// The source iterator will only be driven until the target place is fully
/// initialized. If it [references to] another longer iterator, the remaining
/// items will not be drained.
///
/// # Errors
///
/// The initialization fails if:
///
/// - The iterator produces fewer items than the length of the place, and;
/// - For `str` initialization, the target length is not a valid UTF-8 boundary
///   in the concatenated string.
///
/// Upon error, any elements that have already been initialized are properly
/// dropped to prevent memory leaks; the number of items produced by the
/// iterator is not specified.
///
/// # Examples
///
/// ```rust
/// use placid::prelude::*;
///
/// let source = (1..).map(|x| x * 2);
/// let mut uninit = uninit!([i32; 5]);
/// let owned = uninit.write(init::from_iter(source));
/// assert_eq!(&*owned, &[2, 4, 6, 8, 10]);
///
/// let chars = ['H', 'e', 'l', 'l', 'o'];
/// let mut uninit_str: Uninit<str> = uninit!([u8; 5]);
/// let owned_str = uninit_str.write(init::from_iter(chars));
/// assert_eq!(&*owned_str, "Hello");
///
/// let failing_chars = ['P', '💣'];
/// let mut uninit_str: Uninit<str> = uninit!([u8; 3]);
/// // Fails because '💣' is 4 bytes and doesn't fit in the remaining space
/// uninit_str.try_write(init::from_iter(failing_chars)).unwrap_err();
/// ```
///
/// [references to]: Iterator::by_ref
#[inline]
pub const fn from_iter<I, T>(iter: I) -> FromIter<I, T>
where
    I: IntoIterator<Item = T>,
{
    FromIter(iter, PhantomData)
}

/// Initializes a slice by invoking an incremental closure.
///
/// This initializer is created by the [`incremental()`] factory function.
#[derive(Debug, PartialEq)]
pub struct Incremental<F, A: ?Sized, T>(F, PhantomData<fn(&mut A) -> T>);

impl<F, A: ?Sized, T> Initializer for Incremental<F, A, T> {
    type Error = Infallible;
}

fn write_inc_slice<T, F>(uninit: &mut [MaybeUninit<T>], mut f: F)
where
    F: FnMut(&mut [T]) -> T,
{
    struct Guard<'a, T> {
        slice: &'a mut [MaybeUninit<T>],
        initialized: usize,
    }

    impl<'a, T> Guard<'a, T> {
        fn initialized(&mut self) -> &mut [T] {
            let init_part = &mut self.slice[..self.initialized];
            // SAFETY: this raw sub-slice will contain only initialized objects.
            unsafe { init_part.assume_init_mut() }
        }

        fn write(&mut self, v: T) {
            self.slice[self.initialized].write(v);
            self.initialized += 1;
        }
    }

    impl<'a, T> Drop for Guard<'a, T> {
        fn drop(&mut self) {
            let initialized_part = &mut self.slice[..self.initialized];
            // SAFETY: this raw sub-slice will contain only initialized objects.
            unsafe {
                initialized_part.assume_init_drop();
            }
        }
    }

    let mut guard = Guard { slice: uninit, initialized: 0 };
    for _ in 0..guard.slice.len() {
        let next = f(guard.initialized());
        guard.write(next);
    }
    mem::forget(guard);
}

#[inline]
fn write_inc_array<T, F, const N: usize>(uninit: &mut MaybeUninit<[T; N]>, f: F)
where
    F: FnMut(&mut [T]) -> T,
{
    write_inc_slice(maybe_uninit_slice(uninit), f)
}

fn write_inc_str<'t, F>(uninit: &mut [MaybeUninit<u8>], mut f: F)
where
    F: FnMut(&mut str) -> &'t str,
{
    let mut initialized = 0;
    let total = uninit.len();
    let dst = uninit.as_mut_ptr().cast::<u8>();

    loop {
        let next = f(unsafe {
            let init = core::slice::from_raw_parts_mut(dst, initialized);
            core::str::from_utf8_unchecked_mut(init)
        });

        let bytes = next.as_bytes();
        let len = (total - initialized).min(bytes.len());

        // Checks if `len` is a valid code point boundary.
        assert!(
            next.is_char_boundary(len),
            "invalid UTF-8 boundary in incremental initialization"
        );

        unsafe { ptr::copy_nonoverlapping(bytes.as_ptr(), dst.add(initialized), len) };
        initialized += len;

        if initialized == total {
            break;
        }
    }
}

fn write_inc_chars<F>(uninit: &mut [MaybeUninit<u8>], mut f: F)
where
    F: FnMut(&mut str) -> char,
{
    let mut initialized = 0;
    let total = uninit.len();
    let dst = uninit.as_mut_ptr().cast::<u8>();

    loop {
        let next = f(unsafe {
            let init = core::slice::from_raw_parts_mut(dst, initialized);
            core::str::from_utf8_unchecked_mut(init)
        });

        assert!(
            initialized + next.len_utf8() <= total,
            "not enough space for next char in incremental initialization"
        );

        let mut buf = [0; 4];
        let bytes = next.encode_utf8(&mut buf).as_bytes();

        unsafe { ptr::copy_nonoverlapping(bytes.as_ptr(), dst.add(initialized), bytes.len()) };
        initialized += bytes.len();

        if initialized == total {
            break;
        }
    }
}

macro_rules! derive_incremental {
    (@COERCED $ty:ty |[$coerced:ty]) => { $coerced };
    (@COERCED $ty:ty) => { $ty };
    ($($(@[$($g:tt)*]:)? $item:ty => $ty:ty $(|[$coerced:ty])? = $imp:ident),* $(,)?) => {$(
        impl<$($($g)*,)? __F> InitPin<$ty> for Incremental<
            __F,
            derive_incremental!(@COERCED $ty $(|[$coerced])?),
            $item,
        >
        where
            __F: FnMut(
                &mut derive_incremental!(@COERCED $ty $(|[$coerced])?)
            ) -> $item,
        {
            fn init_pin<'a, 'b>(
                self,
                mut place: Uninit<'a, $ty>,
                slot: DropSlot<'a, 'b, $ty>,
            ) -> InitPinResult<'a, 'b, $ty, Infallible> {
                $imp(&mut *place, self.0);
                Ok(unsafe { place.assume_init_pin(slot) })
            }
        }

        impl<$($($g)*,)? __F> Init<$ty> for Incremental<
            __F,
            derive_incremental!(@COERCED $ty $(|[$coerced])?),
            $item,
        >
        where
            __F: FnMut(
                &mut derive_incremental!(@COERCED $ty $(|[$coerced])?)
            ) -> $item,
        {
            fn init(self, mut place: Uninit<'_, $ty>) -> InitResult<'_, $ty, Infallible> {
                $imp(&mut *place, self.0);
                Ok(unsafe { place.assume_init() })
            }
        }
    )*};
}

derive_incremental! {
    @[T]:                 T => [T]           = write_inc_slice,
    @[T, const N: usize]: T => [T; N] |[[T]] = write_inc_array,

    @['t]: &'t str => str = write_inc_str,
              char => str = write_inc_chars,
}

/// Initializes a slice/str by invoking an incremental closure.
///
/// This is used to initialize a slice/str by repeatedly calling a closure that
/// produces the next element based on the elements initialized so far. This
/// allows for complex initialization patterns that depend on previously
/// initialized elements.
///
/// # Examples
///
/// ```rust
/// use placid::prelude::*;
///
/// let mut uninit = uninit!([Box<i32>; 5]);
/// let owned = uninit.write(init::incremental(|init: &mut [Box<i32>]| {
///     match init {
///         [] => Box::new(1),
///         [.., last] => Box::new(**last * 2),
///     }
/// }));
/// assert!(owned.iter().map(|x| **x).eq([1, 2, 4, 8, 16]));
///
/// let mut uninit_str: Uninit<str> = uninit!([u8; 11]);
/// let owned_str = uninit_str.write(init::incremental(|init: &mut str| {
///     match &*init {
///         "" => "Hello",
///         s => if s.len() <= 5 {
///             init.make_ascii_uppercase();
///             " "
///         } else {
///             "world!"
///         },
///     }
/// }));
/// // The "!" is truncated because the total length is only 11 bytes.
/// assert_eq!(&*owned_str, "HELLO world");
/// ```
#[inline]
pub const fn incremental<A: ?Sized, T, F>(f: F) -> Incremental<F, A, T>
where
    F: FnMut(&mut A) -> T,
{
    Incremental(f, PhantomData)
}