diff options
| author | Emilio Cobos Álvarez <emilio@crisal.io> | 2019-11-05 19:27:42 +0100 |
|---|---|---|
| committer | Emilio Cobos Álvarez <emilio@crisal.io> | 2019-11-05 19:27:42 +0100 |
| commit | b12e142bc5a6f6312ce2fd3305f449d03410a37a (patch) | |
| tree | cec02ddb1e77c3a4b0a3f33b89fc6f7637638179 /src/liballoc/boxed.rs | |
| parent | 3a1b3b30c6cdd674049b144a3ced7b711de962b2 (diff) | |
| download | rust-b12e142bc5a6f6312ce2fd3305f449d03410a37a.tar.gz rust-b12e142bc5a6f6312ce2fd3305f449d03410a37a.zip | |
alloc: Add new_zeroed() versions like new_uninit().
MaybeUninit has both uninit() and zeroed(), it seems reasonable to have the same surface on Box/Rc/Arc. Needs tests.
Diffstat (limited to 'src/liballoc/boxed.rs')
| -rw-r--r-- | src/liballoc/boxed.rs | 27 |
1 files changed, 27 insertions, 0 deletions
diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index 567b8ea7224..51ad3a04e87 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -152,6 +152,33 @@ impl<T> Box<T> { Box(ptr.cast().into()) } + /// Constructs a new `Box` with uninitialized contents, with the memory + /// being filled with `0` bytes. + /// + /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage + /// of this method. + /// + /// # Examples + /// + /// ``` + /// #![feature(new_uninit)] + /// + /// let zero = Box::<u32>::new_zeroed(); + /// let zero = unsafe { zero.assume_init() }; + /// + /// assert_eq!(*zero, 0) + /// ``` + /// + /// [zeroed]: ../../std/mem/union.MaybeUninit.html#method.zeroed + #[unstable(feature = "new_uninit", issue = "63291")] + pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> { + unsafe { + let mut uninit = Self::new_uninit(); + ptr::write_bytes::<T>(uninit.as_mut_ptr(), 0, 1); + uninit + } + } + /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then /// `x` will be pinned in memory and unable to be moved. #[stable(feature = "pin", since = "1.33.0")] |
