Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 9b57963

Browse files
committedSep 5, 2019
Attempt to create Rc/Arc default values in place
1 parent b0674d3 commit 9b57963

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed
 

‎src/liballoc/rc.rs

+13-1
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,18 @@ impl<T> Rc<T> {
358358
}
359359
}
360360

361+
#[inline(always)]
362+
fn new_in_place(f: impl FnOnce() -> T) -> Rc<T> {
363+
let mut r: Rc<mem::MaybeUninit<T>> = Rc::new_uninit();
364+
365+
unsafe {
366+
let uninit: &mut mem::MaybeUninit<T> = Rc::get_mut_unchecked(&mut r);
367+
368+
*uninit = mem::MaybeUninit::new(f());
369+
r.assume_init()
370+
}
371+
}
372+
361373
/// Constructs a new `Pin<Rc<T>>`. If `T` does not implement `Unpin`, then
362374
/// `value` will be pinned in memory and unable to be moved.
363375
#[stable(feature = "pin", since = "1.33.0")]
@@ -1146,7 +1158,7 @@ impl<T: Default> Default for Rc<T> {
11461158
/// ```
11471159
#[inline]
11481160
fn default() -> Rc<T> {
1149-
Rc::new(Default::default())
1161+
Rc::new_in_place(T::default)
11501162
}
11511163
}
11521164

‎src/liballoc/sync.rs

+13-1
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,18 @@ impl<T> Arc<T> {
338338
}
339339
}
340340

341+
#[inline(always)]
342+
fn new_in_place(f: impl FnOnce() -> T) -> Arc<T> {
343+
let mut r: Arc<mem::MaybeUninit<T>> = Arc::new_uninit();
344+
345+
unsafe {
346+
let uninit: &mut mem::MaybeUninit<T> = Arc::get_mut_unchecked(&mut r);
347+
348+
*uninit = mem::MaybeUninit::new(f());
349+
r.assume_init()
350+
}
351+
}
352+
341353
/// Constructs a new `Pin<Arc<T>>`. If `T` does not implement `Unpin`, then
342354
/// `data` will be pinned in memory and unable to be moved.
343355
#[stable(feature = "pin", since = "1.33.0")]
@@ -1933,7 +1945,7 @@ impl<T: Default> Default for Arc<T> {
19331945
/// assert_eq!(*x, 0);
19341946
/// ```
19351947
fn default() -> Arc<T> {
1936-
Arc::new(Default::default())
1948+
Arc::new_in_place(T::default)
19371949
}
19381950
}
19391951

0 commit comments

Comments
 (0)
Please sign in to comment.