diff options
| author | est31 <MTest31@outlook.com> | 2021-06-25 00:02:44 +0200 |
|---|---|---|
| committer | est31 <MTest31@outlook.com> | 2021-06-25 00:54:34 +0200 |
| commit | 5585cce06c19524b5e8f44dcbe8de80af5083cf8 (patch) | |
| tree | 5786462e2cd4614d231563bee427b1c870351b99 | |
| parent | 1c8033f77fc9e394bbc4ba28b29e0be081341b17 (diff) | |
| download | rust-5585cce06c19524b5e8f44dcbe8de80af5083cf8.tar.gz rust-5585cce06c19524b5e8f44dcbe8de80af5083cf8.zip | |
Add another example
| -rw-r--r-- | library/core/src/mem/maybe_uninit.rs | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/library/core/src/mem/maybe_uninit.rs b/library/core/src/mem/maybe_uninit.rs index ab8d6ace29b..e797227c85b 100644 --- a/library/core/src/mem/maybe_uninit.rs +++ b/library/core/src/mem/maybe_uninit.rs @@ -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)] |
