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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
//! Safe abstractions around pointing at uninitialized memory without references.
//!
//! It is potentially **UB** to have references to uninitialized memory even if such a reference is
//! not 'used' in any particular manner. See [the discussion of the unsafe working group][wg-ref].
//!
//! [wg-ref]: https://github.com/rust-lang/unsafe-code-guidelines/issues/77
use core::{fmt, mem, slice, ptr};
use core::alloc::Layout;
use core::marker::PhantomData;

use crate::boxed::Box;

/// Points to an uninitialized place but would otherwise be a valid reference.
///
/// This is a `&mut`-like struct that is somewhat of a pendant to `MaybeUninit`. It makes it
/// possible to deal with uninitialized allocations without requiring an `unsafe` block
/// initializing them and offers a much safer interface for partial initialization and layout
/// calculations than raw pointers.
///
/// Note that it also supports slices which means it does not use `MaybeUninit` internally but
/// offers conversion where necessary.
///
/// ## Usage
///
/// The basic usage is also interacting with `MaybeUninit`:
///
/// ```
/// # #[derive(Default)]
/// # struct MyStruct { };
/// use core::mem::MaybeUninit;
/// use static_alloc::Uninit;
///
/// let mut alloc: MaybeUninit<MyStruct> = MaybeUninit::uninit();
/// let uninit = Uninit::from_maybe_uninit(&mut alloc);
///
/// // notice: no unsafe
/// let instance: &mut MyStruct = uninit.init(MyStruct::default());
/// ```
///
/// But since we are working on arbitrary uninitialized memory it is also possible to reuse the
/// structure for completely arbitrary other types. Just note that there is no integrated mechanis
/// for calling `Drop`.
///
/// ```
/// use core::mem::MaybeUninit;
/// use static_alloc::Uninit;
///
/// // Just a generic buffer.
/// let mut alloc: MaybeUninit<[u32; 1024]> = MaybeUninit::uninit();
/// let uninit = Uninit::from_maybe_uninit(&mut alloc);
///
/// // Now use the first `u32` for a counter:
/// let mut counter = uninit.cast().unwrap();
/// let mut tail = counter.split_to_fit();
/// let counter: &mut u32 = counter.init(0);
///
/// // And some more for a few `u64`.
/// // Note that these are not trivially aligned, but `Uninit` does that for us.
/// let mut values = tail.split_cast().unwrap();
/// // No more use, so don't bother with `split_to_fit` and just `init`.
/// let values: &mut [u64; 2] = values.init([0xdead, 0xbeef]);
/// ```
#[must_use = "This is a pointer-like type that has no effect on its own. Use `init` to insert a value."]
pub struct Uninit<'a, T: ?Sized> {
    /// The underlying view.
    ///
    /// Uninit additional imposes on it that the underlying memory is mutable.
    view: UninitView<'a, T>,

    /// Reminder for every construction.
    mutable: PhantomData<&'a mut ()>,
}

/// A non-mutable view on a region used in an [`Uninit`].
///
/// Makes it possible to utilize the traversal methods (`split*`, `cast*`, ..) without requiring a
/// mutable reference to the original `Uninit`. It will also never expose mutable pointers or
/// accidentally offer an aliased mutable reference. Prefer this to instead avoiding the borrow of
/// the `Uninit` and manually managing pointers to the region.
///
/// [`Uninit`]: ./struct.Uninit.html
#[must_use = "This is a pointer-like type that has no effect on its own."]
pub struct UninitView<'a, T: ?Sized> {
    /// Pointer to the start of the region.
    ///
    /// Note that `len` is always at least as large as the (minimum) size of `T`. Furthermore, the
    /// pointer is always correctly aligned to a `T`.
    ptr: ptr::NonNull<u8>,

    /// The actual length *in bytes*.
    ///
    /// May be larger than required.
    len: usize,

    /// Virtual lifetime to make this behave more similar to references.
    ///
    /// This borrows structures that hand out `Uninit` allocations.
    lifetime: PhantomData<&'a ()>,

    /// We'll be holding an actual `NonNull<T>` in the future (when dynamically sized pointers to
    /// slices are more ergonomic). For now, just type ourselves.
    typed: PhantomData<*mut T>,
}

impl Uninit<'_, ()> {
    /// Create a uninit pointer from raw memory.
    ///
    /// ## Safety
    /// A valid allocation must exist at the pointer with length at least `len`. There must be *no*
    /// references aliasing the memory location, and it must be valid to write uninitialized bytes
    /// into arbitrary locations of the region.
    ///
    /// In particular, it is **UB** to create this from a reference to a variable of a type for
    /// which a completely uninitialized content is not valid. The standard type for avoiding the
    /// UB is `core::mem::MaybeUninit`.
    ///
    /// When in doubt, refactor code such that utilization of `from_maybe_uninit` is possible.
    pub unsafe fn from_memory(ptr: ptr::NonNull<u8>, len: usize) -> Self {
        Uninit::from_presumed_mutable_view(UninitView {
            ptr,
            len,
            lifetime: PhantomData,
            typed: PhantomData,
        })
    }

    /// Split so that the second part fits the layout.
    ///
    /// Return `Ok` if this is possible in-bounds and `Err` if it is not.
    pub fn split_layout(&mut self, layout: Layout) -> Option<Self> {
        self.view.split_layout(layout)
            .map(Self::from_presumed_mutable_view)
    }
}

impl<'a> Uninit<'a, ()> {
    fn decast<T: ?Sized>(uninit: Uninit<'a, T>) -> Self {
        Uninit::from_presumed_mutable_view(UninitView {
            ptr: uninit.view.ptr.cast(),
            len: uninit.view.len,
            lifetime: PhantomData,
            typed: PhantomData,
        })
    }

    /// Split so that the tail is aligned and valid for a `U`.
    ///
    /// Return `Ok` if this is possible in-bounds (aligned and enough room for at least one `U`)
    /// and `Err` if it is not. The first tuple element is the `Uninit` pointing to the skipped
    /// memory.
    pub fn split_cast<U>(&mut self) -> Option<Uninit<'a, U>> {
        let split = self.split_layout(Layout::new::<U>())?;
        let cast = split.cast::<U>().unwrap();
        Some(cast)
    }

    /// Split so that the tail is aligned for a slice `[U]`.
    ///
    /// Return `Ok` if this is possible in-bounds and `Err` if it is not. The first tuple element
    /// is the `Uninit` pointing to the skipped memory.
    ///
    /// The length of the slice is the arbitrary amount that fits into the tail of the allocation.
    /// Note that the length always fulfills the safety requirements for `slice::from_raw_parts`
    /// since the `Uninit` must be contained in a single allocation.
    pub fn split_slice<U>(&mut self) -> Option<Uninit<'a, [U]>> {
        let layout = Layout::for_value::<[U]>(&[]);
        let split = self.split_layout(layout)?;
        let cast = split.cast_slice::<U>().unwrap();
        Some(cast)
    }
}

impl<T> Uninit<'_, T> {
    /// Invent a new uninit allocation for a zero-sized type (ZST).
    ///
    /// # Panics
    /// This method panics when the type parameter is not a zero sized type.
    pub fn invent_for_zst() -> Self {
        // SAFETY: zst is always unaliased.
        unsafe { Uninit::from_view(UninitView::invent_for_zst()) }
    }
}

impl<'a, T> Uninit<'a, T> {
    /// Create an `uninit` from a view.
    ///
    /// ## Safety
    /// The caller must prove that the pointed-to memory is mutable and that it is unaliased.
    pub unsafe fn from_view(view: UninitView<'a, T>) -> Self {
        Self::from_presumed_mutable_view(view)
    }

    /// Create an initializable pointer to the inner bytes of a `MaybeUninit`.
    pub fn from_maybe_uninit(mem: &'a mut mem::MaybeUninit<T>) -> Self {
        let ptr = ptr::NonNull::new(mem.as_mut_ptr()).unwrap();
        let raw = unsafe {
            // SAFETY:
            // * unaliased as we had a mutable reference
            // * can write uninitialized bytes as much as we want
            Uninit::from_memory(ptr.cast(), mem::size_of_val(mem))
        };
        raw.cast().unwrap()
    }

    /// Split the uninit slice at a byte boundary.
    ///
    /// Return `Ok` if the location is in-bounds and `Err` if it is out of bounds.
    pub fn split_at_byte(&mut self, at: usize) -> Option<Uninit<'a, ()>> {
        self.view.split_at_byte(at)
            .map(Uninit::from_presumed_mutable_view)
    }

    /// Try to cast to an `Uninit` for another type.
    ///
    /// Return `Ok` if the current `Uninit` is suitably aligned and large enough to hold at least
    /// one `U` and `Err` if it is not. Note that the successful result points to unused remaining
    /// memory behind where the instance can be placed.
    ///
    /// Use [`split_to_fit`] to get rid of surplus memory at the end.
    ///
    /// [`split_to_fit`]: #method.split_to_fit
    pub fn cast<U>(self) -> Result<Uninit<'a, U>, Self> {
        self.view.cast()
            .map(Uninit::from_presumed_mutable_view)
            .map_err(Self::from_presumed_mutable_view)
    }

    /// Try to cast to an `Uninit` for a slice type.
    ///
    /// Return `Ok` if the current `Uninit` is suitably aligned and large enough to hold at least
    /// one `U` and `Err` if it is not. Note that the successful result points to unused remaining
    /// memory behind where the instances can be placed.
    pub fn cast_slice<U>(self) -> Result<Uninit<'a, [U]>, Self> {
        self.view.cast_slice::<U>()
            .map(Uninit::from_presumed_mutable_view)
            .map_err(Self::from_presumed_mutable_view)
    }

    /// Split off the tail that is not required for holding an instance of `T`.
    ///
    /// This operation is idempotent.
    pub fn split_to_fit(&mut self) -> Uninit<'a, ()> {
        self.split_at_byte(mem::size_of::<T>()).unwrap()
    }

    /// Initialize the place and return a reference to the value.
    pub fn init(self, val: T) -> &'a mut T {
        let ptr = self.as_ptr();
        unsafe {
            // SAFETY:
            // * can only create instances where layout of `T` 'fits'
            // * valid for lifetime `'a` (as per `UninitView`).
            // * unaliased for lifetime `'a` (as per own invariant from unsafe constructor). No
            //   other method duplicates the pointer or allows a second `Uninit` without borrowing
            //   the first.
            ptr::write(ptr, val);
            &mut *ptr
        }
    }

    /// Acquires the underlying *mut pointer.
    pub const fn as_ptr(&self) -> *mut T {
        self.view.ptr.cast().as_ptr()
    }

    /// Acquires the underlying pointer as a `NonNull`.
    pub const fn as_non_null(&self) -> ptr::NonNull<T> {
        self.view.ptr.cast()
    }

    /// Dereferences the content.
    ///
    /// The resulting lifetime is bound to self so this behaves "as if" it were actually an
    /// instance of T that is getting borrowed. If a longer lifetime is needed, use `into_ref`.
    pub unsafe fn as_ref(&self) -> &T {
        self.view.as_ref()
    }

    /// Mutably dereferences the content.
    ///
    /// The resulting lifetime is bound to self so this behaves "as if" it were actually an
    /// instance of T that is getting borrowed. If a longer lifetime is needed, use `into_mut`.
    pub unsafe fn as_mut(&mut self) -> &mut T {
        &mut *self.as_ptr()
    }

    /// Turn this into a reference to the content.
    pub unsafe fn into_ref(self) -> &'a T {
        &*self.as_ptr()
    }

    /// Turn this into a mutable reference to the content.
    pub unsafe fn into_mut(self) -> &'a mut T {
        &mut *self.as_ptr()
    }

    /// Turn this into a reference to standard `MaybeUninit`.
    ///
    /// This is mainly useful for interfacing with other consumers which expect standard library
    /// types. It may also improve ergonomics for writing to the pointee partially initialized
    /// instances of `T` that are obtained via other means.
    ///
    /// Note that the sequence `from_maybe_uninit`, `into_maybe_uninit` is a no-op. The converse is
    /// however not the case, as it will potentially discard unused padding present in the original
    /// `Uninit`.
    pub fn into_maybe_uninit(self) -> &'a mut mem::MaybeUninit<T> {
        // SAFETY: MaybeUninit is a transparent wrapper and need not be initialized.
        unsafe { &mut*(self.as_ptr() as *mut mem::MaybeUninit<T>) }
    }

    /// Utilize this `Uninit` allocation for a boxed value.
    ///
    /// Stores the value at the pointed-to location and utilizes the `Box` as a RAII-guard to
    /// properly drop the value when the box itself is dropped.
    pub fn into_box(self, val: T) -> Box<'a, T> {
        Box::new(val, self)
    }

    /// Read a value from the uninit place without moving it.
    ///
    /// The `Uninit` ensures that the inner pointer is correctly aligned, non-null, and points to a
    /// large enough region for reading a `T`.
    ///
    /// ## Safety
    /// Caller must ensure that the memory is initialized as a valid `T`. It must also avoid double
    /// `Drop`. Basically, a new instance is created.
    pub unsafe fn read(&self) -> T {
        ptr::read(self.as_ptr())
    }
}

impl<'a, T> Uninit<'a, [T]> {
    /// Creates a pointer to an empty slice.
    pub fn empty() -> Self {
        Uninit::from_presumed_mutable_view(UninitView {
            ptr: ptr::NonNull::<T>::dangling().cast(),
            len: 0,
            lifetime: PhantomData,
            typed: PhantomData,
        })
    }

    /// Create an initializable pointer to the inner bytes of a `MaybeUninit`.
    pub fn from_maybe_uninit_slice(mem: &'a mut [mem::MaybeUninit<T>]) -> Self {
        let size = mem::size_of_val(mem);
        let ptr = ptr::NonNull::from(mem);
        let raw = unsafe {
            // SAFETY:
            // * unaliased as we had a mutable reference
            // * can write uninitialized bytes as much as we want
            Uninit::from_memory(ptr.cast(), size)
        };
        raw.cast_slice().unwrap()
    }

    /// Get the pointer to the first element of the slice.
    ///
    /// If the slice would be empty then the pointer may be the past-the-end pointer as well.
    pub const fn as_begin_ptr(&self) -> *mut T {
        self.view.ptr.as_ptr() as *mut T
    }

    /// Calculate the theoretical capacity of a slice in the pointed-to allocation.
    pub fn capacity(&self) -> usize {
        self.view.capacity()
    }

    /// Split the slice at an index.
    ///
    /// This is the pointer equivalent of `slice::split_at`.
    pub fn split_at(&mut self, at: usize) -> Option<Self> {
        self.view.split_at(at)
            .map(Self::from_presumed_mutable_view)
    }

    /// Get the trailing bytes behind the slice.
    ///
    /// The underlying allocation need not be a multiple of the slice element size which may leave
    /// unusable bytes. This splits these unusable bytes into an untyped `Uninit` which can be
    /// reused arbitrarily.
    ///
    /// This operation is idempotent.
    pub fn shrink_to_fit(&mut self) -> Uninit<'a, ()> {
        Uninit::decast(self.split_at(self.capacity()).unwrap())
    }

    /// Split the first element from the slice.
    ///
    /// This is the pointer equivalent of `slice::split_first`.
    pub fn split_first(&mut self) -> Option<Uninit<'a, T>> {
        let mut part = self.split_at(1)?;
        // Now we are the first part, but we wanted the first to be split off.
        mem::swap(self, &mut part);
        // If it is a valid slice of length 1 it is a valid `T`.
        Some(Uninit::decast(part).cast().unwrap())
    }

    /// Split the last element from the slice.
    ///
    /// This is the pointer equivalent of `slice::split_last`.
    pub fn split_last(&mut self) -> Option<Uninit<'a, T>> {
        // Explicitely wrap here: If capacity is 0 then `0 < size_of::<T> ` and the split will fail.
        let split = self.capacity().wrapping_sub(1);
        let part = self.split_at(split)?;
        // If it is a valid slice of length 1 it is a valid `T`.
        Some(Uninit::decast(part).cast().unwrap())
    }

    /// Turn this into a slice of standard `MaybeUninit`s.
    ///
    /// This is mainly useful for interfacing with other consumers which expect standard library
    /// types. It may also improve ergonomics for writing to the pointee partially initialized
    /// instances of `T` that are obtained via other means.
    ///
    /// Note that the sequence `from_maybe_uninit_slice`, `into_maybe_uninit_slice` is a no-op. The
    /// converse is however not the case, as it will potentially discard unused padding present in
    /// the original `Uninit`.
    pub fn into_maybe_uninit_slice(self) -> &'a mut [mem::MaybeUninit<T>] {
        unsafe {
            // SAFETY: MaybeUninit is a transparent wrapper and need not be initialized.
            slice::from_raw_parts_mut(
                self.as_begin_ptr() as *mut mem::MaybeUninit<T>,
                self.capacity())
        }
    }
}

impl<'a, T: ?Sized> Uninit<'a, T> {
    /// Check if the view fits some layout.
    ///
    /// The `cast` to a type of the provided layout will work without error.
    pub fn fits(&self, layout: Layout) -> bool {
        self.view.fits(layout)
    }

    /// View the same uninit as untyped memory.
    pub fn as_memory(self) -> Uninit<'a, ()> {
        Uninit::decast(self)
    }

    /// A private version of the unsafe `from_view`.
    ///
    /// This must never be exposed.
    fn from_presumed_mutable_view(view: UninitView<'a, T>) -> Self {
        Uninit {
            view,
            mutable: PhantomData,
        }
    }

    /// Borrow a view of the `Uninit` region.
    ///
    /// This is the equivalent of `&*mut_ref as *const _` but never runs afoul of accidentally
    /// creating an actual reference.
    pub fn borrow(&self) -> UninitView<'_, T> {
        self.view
    }

    /// Borrow the `Uninit` region for a shorter duration.
    ///
    /// This is the equivalent of `&mut *mut_ref as *mut _` but never runs afoul of accidentally
    /// creating an actual reference.
    pub fn borrow_mut(&mut self) -> Uninit<'_, T> {
        Uninit::from_presumed_mutable_view(self.view)
    }

    /// Get the byte size of the total allocation.
    pub const fn size(&self) -> usize {
        self.view.size()
    }
}
impl UninitView<'_, ()> {
    /// Create a uninit view from raw memory.
    ///
    /// ## Safety
    /// A valid allocation must exist at the pointer with length at least `len`.
    ///
    /// In particular, it is **UB** to create this from a reference to a variable of a type for
    /// which a completely uninitialized content is not valid. The standard type for avoiding the
    /// UB is `core::mem::MaybeUninit`.
    ///
    /// When in doubt, refactor code such that utilization of `from_maybe_uninit` is possible.
    pub unsafe fn from_memory(ptr: ptr::NonNull<u8>, len: usize) -> Self {
        UninitView {
            ptr,
            len,
            lifetime: PhantomData,
            typed: PhantomData,
        }
    }

    /// Split so that the second part fits the layout.
    ///
    /// See [`Uninit::split_layout`] for more details.
    ///
    /// [`Uninit::split_layout`]: ./struct.Uninit.html#method.split_layout
    pub fn split_layout(&mut self, layout: Layout) -> Option<Self> {
        let align = self.ptr.as_ptr()
            .align_offset(layout.align());
        let aligned_len = self.len
            .checked_sub(align)
            .and_then(|len| len.checked_sub(layout.size()));

        if aligned_len.is_none() {
            return None;
        }

        let aligned = self.split_at_byte(align)?;
        assert!(aligned.fits(layout));
        Some(aligned)
    }
}

impl<'a> UninitView<'a, ()> {
    fn decast<T: ?Sized>(view: UninitView<'a, T>) -> Self {
        UninitView {
            ptr: view.ptr.cast(),
            len: view.len,
            lifetime: PhantomData,
            typed: PhantomData,
        }
    }

    /// Split so that the tail is aligned and valid for a `U`.
    pub fn split_cast<U>(&mut self) -> Option<UninitView<'a, U>> {
        let split = self.split_layout(Layout::new::<U>())?;
        let cast = split.cast::<U>().unwrap();
        Some(cast)
    }

    /// Split so that the tail is aligned for a slice `[U]`.
    pub fn split_slice<U>(&mut self) -> Option<UninitView<'a, [U]>> {
        let layout = Layout::for_value::<[U]>(&[]);
        let split = self.split_layout(layout)?;
        let cast = split.cast_slice::<U>().unwrap();
        Some(cast)
    }
}

impl<T> UninitView<'_, T> {
    /// Invent a new uninit allocation for a zero-sized type (ZST).
    ///
    /// # Panics
    /// This method panics when the type parameter is not a zero sized type.
    pub fn invent_for_zst() -> Self {
        assert_eq!(mem::size_of::<T>(), 0, "Invented ZST uninit invoked with non-ZST");
        let dangling = ptr::NonNull::<T>::dangling();
        // SAFETY: all bytes are within the allocation.
        let raw = unsafe { UninitView::from_memory(dangling.cast(), 0) };
        raw.cast().unwrap()
    }
}

impl<'a, T> UninitView<'a, T> {
    /// Split the uninit view at a byte boundary.
    ///
    /// See [`Uninit::split_at_byte`] for more details.
    ///
    /// [`Uninit::split_at_byte`]: ./struct.Uninit.html#method.split_at_byte
    pub fn split_at_byte(&mut self, at: usize) -> Option<UninitView<'a, ()>> {
        if self.len < at || at < mem::size_of::<T>() {
            return None;
        }

        let base = self.ptr.as_ptr();
        // SAFETY: by `from_memory`, all offsets `< len` are within the allocation.
        // In particular, no pointer within or one-past-the-end is null.
        let next_base = unsafe { ptr::NonNull::new_unchecked(base.add(at)) };
        let next_len = self.len - at;
        self.len = at;

        // SAFETY: within one allocation, namely the one we are in.
        let other = unsafe { UninitView::from_memory(next_base.cast(), next_len) };
        Some(other)
    }

    /// Create an view to the inner bytes of a `MaybeUninit`.
    ///
    /// This is hardly useful on its own but since `UninitView` mirrors the traversal methods of
    /// `Uninit` it can be used to get pointers to already initialized elements in an immutable
    /// context.
    pub fn from_maybe_uninit(mem: &'a mem::MaybeUninit<T>) -> Self {
        let ptr = ptr::NonNull::new(mem.as_ptr() as *mut T).unwrap();
        let raw = unsafe {
            // SAFETY:
            // * unaliased as we had a mutable reference
            // * we will not write through the pointer created
            UninitView::from_memory(ptr.cast(), mem::size_of_val(mem))
        };
        raw.cast().unwrap()
    }

    /// Try to cast to an `UninitView` for another type.
    pub fn cast<U>(self) -> Result<UninitView<'a, U>, Self> {
        if !self.fits(Layout::new::<U>()) {
            return Err(self);
        }

        Ok(UninitView {
            ptr: self.ptr.cast(),
            len: self.len,
            lifetime: PhantomData,
            typed: PhantomData,
        })
    }

    /// Try to cast to an `UninitView` for a slice type.
    pub fn cast_slice<U>(self) -> Result<UninitView<'a, [U]>, Self> {
        let empty = Layout::for_value::<[U]>(&[]);

        if !self.fits(empty) {
            return Err(self)
        }

        Ok(UninitView {
            ptr: self.ptr,
            len: self.len,
            lifetime: PhantomData,
            typed: PhantomData,
        })
    }

    /// Split off the tail that is not required for holding an instance of `T`.
    pub fn split_to_fit(&mut self) -> UninitView<'a, ()> {
        self.split_at_byte(mem::size_of::<T>()).unwrap()
    }

    /// Acquires the underlying `*const T` pointer.
    pub const fn as_ptr(&self) -> *const T {
        self.ptr.as_ptr() as *const T
    }

    /// Acquires the underlying pointer as a `NonNull`.
    pub fn as_non_null(&self) -> ptr::NonNull<T> {
        self.ptr.cast()
    }

    /// Dereferences the content.
    ///
    /// The resulting lifetime is bound to self so this behaves "as if" it were actually an
    /// instance of T that is getting borrowed. If a longer lifetime is needed, use `into_ref`.
    ///
    /// ## Safety
    /// The caller must ensure that the content has already been initialized.
    pub unsafe fn as_ref(&self) -> &T {
        self.into_ref()
    }

    /// Turn this into a reference to the content.
    ///
    /// ## Safety
    /// The caller must ensure that the content has already been initialized.
    pub unsafe fn into_ref(self) -> &'a T {
        &*self.as_ptr()
    }

    /// Turn this into a reference to standard `MaybeUninit`.
    ///
    /// This is mainly useful for interfacing with other consumers which expect standard library
    /// types and to mirror `Uninit`.
    ///
    /// Note that the sequence `from_maybe_uninit`, `into_maybe_uninit` is a no-op. The converse is
    /// however not the case, as it will potentially discard unused padding present in the original
    /// `Uninit`.
    pub fn into_maybe_uninit(self) -> &'a mem::MaybeUninit<T> {
        // SAFETY: MaybeUninit is a transparent wrapper and need not be initialized.
        unsafe { &*(self.as_ptr() as *const mem::MaybeUninit<T>) }
    }
}

impl<'a, T> UninitView<'a, [T]> {
    /// Creates a pointer to an empty slice.
    ///
    /// Note that it will **not** be a mutable empty slice which means that it would be **UB** to
    /// use it as an `Uninit`.
    pub fn empty() -> Self {
        UninitView {
            ptr: ptr::NonNull::<T>::dangling().cast(),
            len: 0,
            lifetime: PhantomData,
            typed: PhantomData,
        }
    }

    /// Create an view on potentially uninitialized memory bytes of a slice of `MaybeUninit`.
    pub fn from_maybe_uninit_slice(mem: &'a [mem::MaybeUninit<T>]) -> Self {
        let ptr = ptr::NonNull::from(mem);
        let raw = unsafe {
            // SAFETY:
            // * can write uninitialized bytes as much as we want
            UninitView::from_memory(ptr.cast(), mem::size_of_val(mem))
        };
        raw.cast_slice().unwrap()
    }

    /// Get the pointer to the first element of the slice.
    pub fn as_begin_ptr(&self) -> *const T {
        self.ptr.as_ptr() as *const T
    }

    /// Calculate the theoretical capacity of a slice in the pointed-to allocation.
    pub fn capacity(&self) -> usize {
        self.size()
            .checked_div(mem::size_of::<T>())
            .unwrap_or_else(usize::max_value)
    }

    /// Split the slice at an index.
    pub fn split_at(&mut self, at: usize) -> Option<Self> {
        // NOTE: Slice pointers are blocked by Rust stabilization we can not create one from a real
        // reference to slice as that would restrict us to the memory covered by the reference.
        // NOTE: Tracked here https://github.com/rust-lang/rust/issues/36925
        let bytes = match at.checked_mul(mem::size_of::<T>()) {
            None => return None,
            Some(byte) if byte > self.len => return None,
            Some(byte) => byte,
        };

        let next_len = self.len - bytes;
        self.len = bytes;

        let base = self.ptr.as_ptr();
        // SAFETY: was previously in bounds.
        let next_base = unsafe { ptr::NonNull::new_unchecked(base.add(bytes)) };

        // SAFETY: total allocation length at least `self.len + next_len`.
        let other = unsafe { UninitView::from_memory(next_base, next_len) };
        Some(other.cast_slice().unwrap())
    }

    /// Get the trailing bytes behind the slice.
    ///
    /// The underlying allocation need not be a multiple of the slice element size which may leave
    /// unusable bytes. This splits these unusable bytes into an untyped `Uninit` which can be
    /// reused arbitrarily.
    ///
    /// This operation is idempotent.
    pub fn shrink_to_fit(&mut self) -> UninitView<'a, ()> {
        UninitView::decast(self.split_at(self.capacity()).unwrap())
    }

    /// Split the first element from the slice.
    pub fn split_first(&mut self) -> Option<UninitView<'a, T>> {
        let mut part = self.split_at(1)?;
        // Now we are the first part, but we wanted the first to be split off.
        mem::swap(self, &mut part);
        // If it is a valid slice of length 1 it is a valid `T`.
        Some(UninitView::decast(part).cast().unwrap())
    }

    /// Split the last element from the slice.
    pub fn split_last(&mut self) -> Option<UninitView<'a, T>> {
        // Explicitely wrap here: If capacity is 0 then `0 < size_of::<T> ` and the split will fail.
        let split = self.capacity().wrapping_sub(1);
        let part = self.split_at(split)?;
        // If it is a valid slice of length 1 it is a valid `T`.
        Some(UninitView::decast(part).cast().unwrap())
    }

    /// Turn this into a slice of standard `MaybeUninit`s.
    ///
    /// This is mainly useful for interfacing with other consumers which expect standard library
    /// types and to mirror `Uninit`.
    ///
    /// Note that the sequence `from_maybe_uninit_slice`, `into_maybe_uninit_slice` is a no-op. The
    /// converse is however not the case, as it will potentially discard unused padding present in
    /// the original `Uninit`.
    pub fn into_maybe_uninit_slice(self) -> &'a [mem::MaybeUninit<T>] {
        unsafe {
            // SAFETY: MaybeUninit is a transparent wrapper and need not be initialized.
            slice::from_raw_parts(
                self.as_begin_ptr() as *const mem::MaybeUninit<T>,
                self.capacity())
        }
    }
}

impl<'a, T: ?Sized> UninitView<'a, T> {
    /// Check if the view fits some layout.
    ///
    /// The `cast` to a type of the provided layout will work without error.
    pub fn fits(&self, layout: Layout) -> bool {
        self.ptr.as_ptr().align_offset(layout.align()) == 0
            && layout.size() <= self.len
    }

    /// Borrow another view of the `Uninit` region.
    pub fn borrow(&self) -> UninitView<'_, T> {
        *self
    }

    /// Get the byte size of the total allocation.
    pub const fn size(&self) -> usize {
        self.len
    }
}

impl<'a, T> From<&'a mut mem::MaybeUninit<T>> for Uninit<'a, T> {
    fn from(mem: &'a mut mem::MaybeUninit<T>) -> Self {
        Uninit::<T>::from_maybe_uninit(mem)
    }
}

impl<'a, T> From<&'a mut [mem::MaybeUninit<T>]> for Uninit<'a, [T]> {
    fn from(mem: &'a mut [mem::MaybeUninit<T>]) -> Self {
        Uninit::<[T]>::from_maybe_uninit_slice(mem)
    }
}

impl<'a, T> From<&'a mem::MaybeUninit<T>> for UninitView<'a, T> {
    fn from(mem: &'a mem::MaybeUninit<T>) -> Self {
        UninitView::from_maybe_uninit(mem)
    }
}

impl<'a, T> From<&'a [mem::MaybeUninit<T>]> for UninitView<'a, [T]> {
    fn from(mem: &'a [mem::MaybeUninit<T>]) -> Self {
        UninitView::<[T]>::from_maybe_uninit_slice(mem)
    }
}

impl<T: ?Sized> fmt::Debug for Uninit<'_, T> {
   fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
       f.debug_tuple("Uninit")
           .field(&self.view.ptr)
           .field(&self.view.len)
           .finish()
   }
}

impl<T: ?Sized> fmt::Debug for UninitView<'_, T> {
   fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
       f.debug_tuple("UninitView")
           .field(&self.ptr)
           .field(&self.len)
           .finish()
   }
}

impl<'a, T> From<Uninit<'a, T>> for UninitView<'a, T> {
    fn from(uninit: Uninit<'a, T>) -> Self {
        uninit.view
    }
}

impl<T> Default for Uninit<'_, [T]> {
   fn default() -> Self {
       Uninit::empty()
   }
}

impl<T> Default for UninitView<'_, [T]> {
   fn default() -> Self {
       UninitView::empty()
   }
}

impl<T: ?Sized> Clone for UninitView<'_, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T: ?Sized> Copy for UninitView<'_, T> { }

#[cfg(test)]
mod tests {
    use super::Uninit;

    #[test]
    fn lifetime_longer() {
        fn _long<'a, T>(_: Uninit<'a, &'static T>) { }
    }

    #[test]
    fn lifetime_shorter() {
        fn _short<'a, T>(_: Uninit<'static, &'a T>) { }
    }

    #[test]
    fn in_a_struct() {
        enum _List<T> {
            Nil,
            Cons(T, Uninit<'static, T>),
        }
    }
}