Skip to content

Commit

Permalink
Add another example
Browse files Browse the repository at this point in the history
  • Loading branch information
est31 committed Jun 24, 2021
1 parent 1c8033f commit 5585cce
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions library/core/src/mem/maybe_uninit.rs
Expand Up @@ -454,6 +454,36 @@ impl<T> MaybeUninit<T> {
/// // x is initialized now:
/// let s = unsafe { x.assume_init() };
/// ```
///
/// This method can be used to avoid unsafe in some cases. The example below
/// shows a part of an implementation of a fixed sized arena that lends out
/// pinned references.
/// With `write`, we can avoid the need to write through a raw pointer:
///
/// ```rust
/// #![feature(maybe_uninit_extra)]
/// use core::pin::Pin;
/// use core::mem::MaybeUninit;
///
/// struct PinArena<T> {
/// memory: Box<[MaybeUninit<T>]>,
/// len: usize,
/// }
///
/// impl <T> PinArena<T> {
/// pub fn capacity(&self) -> usize {
/// self.memory.len()
/// }
/// pub fn push(&mut self, val: T) -> Pin<&mut T> {
/// if self.len >= self.capacity() {
/// panic!("Attempted to push to a full pin arena!");
/// }
/// let ref_ = self.memory[self.len].write(val);
/// self.len += 1;
/// unsafe { Pin::new_unchecked(ref_) }
/// }
/// }
/// ```
#[stable(feature = "maybe_uninit_write", since = "1.55.0")]
#[rustc_const_unstable(feature = "const_maybe_uninit_write", issue = "63567")]
#[inline(always)]
Expand Down

0 comments on commit 5585cce

Please sign in to comment.