Skip to content

Commit 1582c18

Browse files
committed
Add helper functions for Array<MaybeUninit<T>, U>
Adds the following functions: - `uninit`: construct an uninitialized `Array<MaybeUninit<T>, U>` - `assume_init`: converts to `Array<T, U>` assuming all elements are initialized
1 parent cf933f4 commit 1582c18

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/lib.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,28 @@ where
217217
}
218218
}
219219

220+
impl<T, U> Array<MaybeUninit<T>, U>
221+
where
222+
U: ArraySize,
223+
{
224+
/// Create an uninitialized array of [`MaybeUninit`]s for the given type.
225+
pub const fn uninit() -> Self {
226+
// SAFETY: an array of `MaybeUninit`s is always valid.
227+
unsafe { MaybeUninit::uninit().assume_init() }
228+
}
229+
230+
/// Extract the values from an array of `MaybeUninit` containers.
231+
///
232+
/// # Safety
233+
///
234+
/// It is up to the caller to guarantee that all elements of the array are in an initialized
235+
/// state.
236+
pub unsafe fn assume_init(self) -> Array<T, U> {
237+
// TODO(tarcieri): use `MaybeUninit::array_assume_init` when stable
238+
ptr::read(self.as_ptr().cast())
239+
}
240+
}
241+
220242
impl<T, U> AsRef<[T]> for Array<T, U>
221243
where
222244
U: ArraySize,

0 commit comments

Comments
 (0)