1 use std::mem;
2 use std::mem::MaybeUninit;
3 use std::slice;
4 
5 /// `Vec::spare_capacity_mut` is not stable until Rust 1.60.
vec_spare_capacity_mut<A>(vec: &mut Vec<A>) -> &mut [MaybeUninit<A>]6 pub(crate) fn vec_spare_capacity_mut<A>(vec: &mut Vec<A>) -> &mut [MaybeUninit<A>] {
7     // SAFETY: copy-paste from rust stdlib.
8     unsafe {
9         slice::from_raw_parts_mut(
10             vec.as_mut_ptr().add(vec.len()) as *mut MaybeUninit<A>,
11             vec.capacity() - vec.len(),
12         )
13     }
14 }
15 
16 /// `MaybeUninit::write_slice` is not stable.
maybe_uninit_write_slice<'a, T>( this: &'a mut [MaybeUninit<T>], src: &[T], ) -> &'a mut [T] where T: Copy,17 pub(crate) fn maybe_uninit_write_slice<'a, T>(
18     this: &'a mut [MaybeUninit<T>],
19     src: &[T],
20 ) -> &'a mut [T]
21 where
22     T: Copy,
23 {
24     // SAFETY: copy-paste from rust stdlib.
25 
26     let uninit_src: &[MaybeUninit<T>] = unsafe { mem::transmute(src) };
27 
28     this.copy_from_slice(uninit_src);
29 
30     unsafe { &mut *(this as *mut [MaybeUninit<T>] as *mut [T]) }
31 }
32 
33 /// `MaybeUninit::array_assume_init` is not stable.
34 #[inline]
maybe_ununit_array_assume_init<T, const N: usize>( array: [MaybeUninit<T>; N], ) -> [T; N]35 pub(crate) unsafe fn maybe_ununit_array_assume_init<T, const N: usize>(
36     array: [MaybeUninit<T>; N],
37 ) -> [T; N] {
38     // SAFETY:
39     // * The caller guarantees that all elements of the array are initialized
40     // * `MaybeUninit<T>` and T are guaranteed to have the same layout
41     // * `MaybeUninit` does not drop, so there are no double-frees
42     // And thus the conversion is safe
43     (&array as *const _ as *const [T; N]).read()
44 }
45 
46 /// `MaybeUninit::write` is stable since 1.55.
47 #[inline]
maybe_uninit_write<T>(uninit: &mut MaybeUninit<T>, val: T) -> &mut T48 pub(crate) fn maybe_uninit_write<T>(uninit: &mut MaybeUninit<T>, val: T) -> &mut T {
49     // SAFETY: copy-paste from rust stdlib.
50     *uninit = MaybeUninit::new(val);
51     unsafe { &mut *uninit.as_mut_ptr() }
52 }
53