| 1 |
#![allow(unused_unsafe)] |
| 2 |
|
| 3 |
//! Contains implementations for rust core that have not been stabilized |
| 4 |
//! |
| 5 |
//! Functions in this are expected to be properly peer reviewed by the community |
| 6 |
//! |
| 7 |
//! Any modifications done are purely to make the code compatible with bincode |
| 8 |
|
| 9 |
use core::mem::{self, MaybeUninit}; |
| 10 |
|
| 11 |
/// Pulls `N` items from `iter` and returns them as an array. If the iterator |
| 12 |
/// yields fewer than `N` items, `None` is returned and all already yielded |
| 13 |
/// items are dropped. |
| 14 |
/// |
| 15 |
/// Since the iterator is passed as a mutable reference and this function calls |
| 16 |
/// `next` at most `N` times, the iterator can still be used afterwards to |
| 17 |
/// retrieve the remaining items. |
| 18 |
/// |
| 19 |
/// If `iter.next()` panicks, all items already yielded by the iterator are |
| 20 |
/// dropped. |
| 21 |
#[allow(clippy::while_let_on_iterator)] |
| 22 |
pub fn collect_into_array<E, I, T, const N: usize>(iter: &mut I) -> Option<Result<[T; N], E>> |
| 23 |
where |
| 24 |
I: Iterator<Item = Result<T, E>>, |
| 25 |
{ |
| 26 |
if N == 0 { |
| 27 |
// SAFETY: An empty array is always inhabited and has no validity invariants. |
| 28 |
return unsafe { Some(Ok(mem::zeroed())) }; |
| 29 |
} |
| 30 |
|
| 31 |
struct Guard<'a, T, const N: usize> { |
| 32 |
array_mut: &'a mut [MaybeUninit<T>; N], |
| 33 |
initialized: usize, |
| 34 |
} |
| 35 |
|
| 36 |
impl<T, const N: usize> Drop for Guard<'_, T, N> { |
| 37 |
fn drop(&mut self) { |
| 38 |
debug_assert!(self.initialized <= N); |
| 39 |
|
| 40 |
// SAFETY: this slice will contain only initialized objects. |
| 41 |
unsafe { |
| 42 |
core::ptr::drop_in_place(slice_assume_init_mut( |
| 43 |
self.array_mut.get_unchecked_mut(..self.initialized), |
| 44 |
)); |
| 45 |
} |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
let mut array = uninit_array::<T, N>(); |
| 50 |
let mut guard = Guard { |
| 51 |
array_mut: &mut array, |
| 52 |
initialized: 0, |
| 53 |
}; |
| 54 |
|
| 55 |
while let Some(item_rslt) = iter.next() { |
| 56 |
let item = match item_rslt { |
| 57 |
Err(err) => { |
| 58 |
return Some(Err(err)); |
| 59 |
} |
| 60 |
Ok(elem) => elem, |
| 61 |
}; |
| 62 |
|
| 63 |
// SAFETY: `guard.initialized` starts at 0, is increased by one in the |
| 64 |
// loop and the loop is aborted once it reaches N (which is |
| 65 |
// `array.len()`). |
| 66 |
unsafe { |
| 67 |
guard |
| 68 |
.array_mut |
| 69 |
.get_unchecked_mut(guard.initialized) |
| 70 |
.write(item); |
| 71 |
} |
| 72 |
guard.initialized += 1; |
| 73 |
|
| 74 |
// Check if the whole array was initialized. |
| 75 |
if guard.initialized == N { |
| 76 |
mem::forget(guard); |
| 77 |
|
| 78 |
// SAFETY: the condition above asserts that all elements are |
| 79 |
// initialized. |
| 80 |
let out = unsafe { array_assume_init(array) }; |
| 81 |
return Some(Ok(out)); |
| 82 |
} |
| 83 |
} |
| 84 |
|
| 85 |
// This is only reached if the iterator is exhausted before |
| 86 |
// `guard.initialized` reaches `N`. Also note that `guard` is dropped here, |
| 87 |
// dropping all already initialized elements. |
| 88 |
None |
| 89 |
} |
| 90 |
|
| 91 |
/// Assuming all the elements are initialized, get a mutable slice to them. |
| 92 |
/// |
| 93 |
/// # Safety |
| 94 |
/// |
| 95 |
/// It is up to the caller to guarantee that the `MaybeUninit<T>` elements |
| 96 |
/// really are in an initialized state. |
| 97 |
/// Calling this when the content is not yet fully initialized causes undefined behavior. |
| 98 |
/// |
| 99 |
/// See [`assume_init_mut`] for more details and examples. |
| 100 |
/// |
| 101 |
/// [`assume_init_mut`]: MaybeUninit::assume_init_mut |
| 102 |
// #[unstable(feature = "maybe_uninit_slice", issue = "63569")] |
| 103 |
// #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init", issue = "none")] |
| 104 |
#[inline(always)] |
| 105 |
pub unsafe fn slice_assume_init_mut<T>(slice: &mut [MaybeUninit<T>]) -> &mut [T] { |
| 106 |
// SAFETY: similar to safety notes for `slice_get_ref`, but we have a |
| 107 |
// mutable reference which is also guaranteed to be valid for writes. |
| 108 |
unsafe { &mut *(slice as *mut [MaybeUninit<T>] as *mut [T]) } |
| 109 |
} |
| 110 |
|
| 111 |
/// Create a new array of `MaybeUninit<T>` items, in an uninitialized state. |
| 112 |
/// |
| 113 |
/// Note: in a future Rust version this method may become unnecessary |
| 114 |
/// when Rust allows |
| 115 |
/// [inline const expressions](https://github.com/rust-lang/rust/issues/76001). |
| 116 |
/// The example below could then use `let mut buf = [const { MaybeUninit::<u8>::uninit() }; 32];`. |
| 117 |
/// |
| 118 |
/// # Examples |
| 119 |
/// |
| 120 |
/// ```ignore |
| 121 |
/// #![feature(maybe_uninit_uninit_array, maybe_uninit_extra, maybe_uninit_slice)] |
| 122 |
/// |
| 123 |
/// use std::mem::MaybeUninit; |
| 124 |
/// |
| 125 |
/// extern "C" { |
| 126 |
/// fn read_into_buffer(ptr: *mut u8, max_len: usize) -> usize; |
| 127 |
/// } |
| 128 |
/// |
| 129 |
/// /// Returns a (possibly smaller) slice of data that was actually read |
| 130 |
/// fn read(buf: &mut [MaybeUninit<u8>]) -> &[u8] { |
| 131 |
/// unsafe { |
| 132 |
/// let len = read_into_buffer(buf.as_mut_ptr() as *mut u8, buf.len()); |
| 133 |
/// MaybeUninit::slice_assume_init_ref(&buf[..len]) |
| 134 |
/// } |
| 135 |
/// } |
| 136 |
/// |
| 137 |
/// let mut buf: [MaybeUninit<u8>; 32] = MaybeUninit::uninit_array(); |
| 138 |
/// let data = read(&mut buf); |
| 139 |
/// ``` |
| 140 |
// #[unstable(feature = "maybe_uninit_uninit_array", issue = "none")] |
| 141 |
// #[rustc_const_unstable(feature = "maybe_uninit_uninit_array", issue = "none")] |
| 142 |
#[inline(always)] |
| 143 |
fn uninit_array<T, const LEN: usize>() -> [MaybeUninit<T>; LEN] { |
| 144 |
// SAFETY: An uninitialized `[MaybeUninit<_>; LEN]` is valid. |
| 145 |
unsafe { MaybeUninit::<[MaybeUninit<T>; LEN]>::uninit().assume_init() } |
| 146 |
} |
| 147 |
|
| 148 |
/// Extracts the values from an array of `MaybeUninit` containers. |
| 149 |
/// |
| 150 |
/// # Safety |
| 151 |
/// |
| 152 |
/// It is up to the caller to guarantee that all elements of the array are |
| 153 |
/// in an initialized state. |
| 154 |
/// |
| 155 |
/// # Examples |
| 156 |
/// |
| 157 |
/// ```ignore |
| 158 |
/// #![feature(maybe_uninit_uninit_array)] |
| 159 |
/// #![feature(maybe_uninit_array_assume_init)] |
| 160 |
/// use std::mem::MaybeUninit; |
| 161 |
/// |
| 162 |
/// let mut array: [MaybeUninit<i32>; 3] = MaybeUninit::uninit_array(); |
| 163 |
/// array[0].write(0); |
| 164 |
/// array[1].write(1); |
| 165 |
/// array[2].write(2); |
| 166 |
/// |
| 167 |
/// // SAFETY: Now safe as we initialised all elements |
| 168 |
/// let array = unsafe { |
| 169 |
/// MaybeUninit::array_assume_init(array) |
| 170 |
/// }; |
| 171 |
/// |
| 172 |
/// assert_eq!(array, [0, 1, 2]); |
| 173 |
/// ``` |
| 174 |
// #[unstable(feature = "maybe_uninit_array_assume_init", issue = "80908")] |
| 175 |
#[inline(always)] |
| 176 |
pub unsafe fn array_assume_init<T, const N: usize>(array: [MaybeUninit<T>; N]) -> [T; N] { |
| 177 |
// SAFETY: |
| 178 |
// * The caller guarantees that all elements of the array are initialized |
| 179 |
// * `MaybeUninit<T>` and T are guaranteed to have the same layout |
| 180 |
// * `MaybeUninit` does not drop, so there are no double-frees |
| 181 |
// And thus the conversion is safe |
| 182 |
unsafe { |
| 183 |
// intrinsics::assert_inhabited::<[T; N]>(); |
| 184 |
(&array as *const _ as *const [T; N]).read() |
| 185 |
} |
| 186 |
} |