Skip to content

Commit

Permalink
Attempt to create Rc/Arc default values in place
Browse files Browse the repository at this point in the history
  • Loading branch information
petertodd committed Sep 5, 2019
1 parent b0674d3 commit 9b57963
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
14 changes: 13 additions & 1 deletion src/liballoc/rc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,18 @@ impl<T> Rc<T> {
}
}

#[inline(always)]
fn new_in_place(f: impl FnOnce() -> T) -> Rc<T> {
let mut r: Rc<mem::MaybeUninit<T>> = Rc::new_uninit();

unsafe {
let uninit: &mut mem::MaybeUninit<T> = Rc::get_mut_unchecked(&mut r);

*uninit = mem::MaybeUninit::new(f());
r.assume_init()
}
}

/// Constructs a new `Pin<Rc<T>>`. If `T` does not implement `Unpin`, then
/// `value` will be pinned in memory and unable to be moved.
#[stable(feature = "pin", since = "1.33.0")]
Expand Down Expand Up @@ -1146,7 +1158,7 @@ impl<T: Default> Default for Rc<T> {
/// ```
#[inline]
fn default() -> Rc<T> {
Rc::new(Default::default())
Rc::new_in_place(T::default)
}
}

Expand Down
14 changes: 13 additions & 1 deletion src/liballoc/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,18 @@ impl<T> Arc<T> {
}
}

#[inline(always)]
fn new_in_place(f: impl FnOnce() -> T) -> Arc<T> {
let mut r: Arc<mem::MaybeUninit<T>> = Arc::new_uninit();

unsafe {
let uninit: &mut mem::MaybeUninit<T> = Arc::get_mut_unchecked(&mut r);

*uninit = mem::MaybeUninit::new(f());
r.assume_init()
}
}

/// Constructs a new `Pin<Arc<T>>`. If `T` does not implement `Unpin`, then
/// `data` will be pinned in memory and unable to be moved.
#[stable(feature = "pin", since = "1.33.0")]
Expand Down Expand Up @@ -1933,7 +1945,7 @@ impl<T: Default> Default for Arc<T> {
/// assert_eq!(*x, 0);
/// ```
fn default() -> Arc<T> {
Arc::new(Default::default())
Arc::new_in_place(T::default)
}
}

Expand Down

0 comments on commit 9b57963

Please sign in to comment.