Skip to content

Commit

Permalink
Rollup merge of rust-lang#132031 - slanterns:rc_default, r=ibraheemdev
Browse files Browse the repository at this point in the history
Optimize `Rc<T>::default`

The missing piece of rust-lang#131460.

Also refactored `Arc<T>::default` by using a safe `NonNull::from(Box::leak(_))` to replace the unnecessarily unsafe call to `NonNull::new_unchecked(Box::into_raw(_))`. The remaining unsafety is coming from `[Rc|Arc]::from_inner`, which is safe from the construction of `[Rc|Arc]Inner`.
  • Loading branch information
matthiaskrgr authored Oct 23, 2024
2 parents 05b4955 + 224a60d commit 054b256
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
11 changes: 10 additions & 1 deletion alloc/src/rc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2312,7 +2312,16 @@ impl<T: Default> Default for Rc<T> {
/// ```
#[inline]
fn default() -> Rc<T> {
Rc::new(Default::default())
unsafe {
Self::from_inner(
Box::leak(Box::write(Box::new_uninit(), RcInner {
strong: Cell::new(1),
weak: Cell::new(1),
value: T::default(),
}))
.into(),
)
}
}
}

Expand Down
17 changes: 10 additions & 7 deletions alloc/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3447,13 +3447,16 @@ impl<T: Default> Default for Arc<T> {
/// assert_eq!(*x, 0);
/// ```
fn default() -> Arc<T> {
let x = Box::into_raw(Box::write(Box::new_uninit(), ArcInner {
strong: atomic::AtomicUsize::new(1),
weak: atomic::AtomicUsize::new(1),
data: T::default(),
}));
// SAFETY: `Box::into_raw` consumes the `Box` and never returns null
unsafe { Self::from_inner(NonNull::new_unchecked(x)) }
unsafe {
Self::from_inner(
Box::leak(Box::write(Box::new_uninit(), ArcInner {
strong: atomic::AtomicUsize::new(1),
weak: atomic::AtomicUsize::new(1),
data: T::default(),
}))
.into(),
)
}
}
}

Expand Down

0 comments on commit 054b256

Please sign in to comment.