From 8f3cb7d75d0271066a11502d331333dc804e5d14 Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Thu, 31 Dec 2020 16:36:28 +0000 Subject: [PATCH] Make [A]Rc::allocate_for_layout() use try_allocate_for_layout() --- library/alloc/src/rc.rs | 15 +++------------ library/alloc/src/sync.rs | 13 ++----------- 2 files changed, 5 insertions(+), 23 deletions(-) diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index afaefaa2565..5f5c3c19a81 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -1107,20 +1107,10 @@ impl Rc { // `&*(ptr as *const RcBox)`, but this created a misaligned // reference (see #54908). let layout = Layout::new::>().extend(value_layout).unwrap().0.pad_to_align(); - - // Allocate for the layout. - let ptr = allocate(layout).unwrap_or_else(|_| handle_alloc_error(layout)); - - // Initialize the RcBox - let inner = mem_to_rcbox(ptr.as_non_null_ptr().as_ptr()); unsafe { - debug_assert_eq!(Layout::for_value(&*inner), layout); - - ptr::write(&mut (*inner).strong, Cell::new(1)); - ptr::write(&mut (*inner).weak, Cell::new(1)); + Rc::try_allocate_for_layout(value_layout, allocate, mem_to_rcbox) + .unwrap_or_else(|_| handle_alloc_error(layout)) } - - inner } /// Allocates an `RcBox` with sufficient space for @@ -1129,6 +1119,7 @@ impl Rc { /// /// The function `mem_to_rcbox` is called with the data pointer /// and must return back a (potentially fat)-pointer for the `RcBox`. + #[inline] unsafe fn try_allocate_for_layout( value_layout: Layout, allocate: impl FnOnce(Layout) -> Result, AllocError>, diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index e8c3d1293e7..83032f7feee 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -1085,19 +1085,10 @@ impl Arc { // `&*(ptr as *const ArcInner)`, but this created a misaligned // reference (see #54908). let layout = Layout::new::>().extend(value_layout).unwrap().0.pad_to_align(); - - let ptr = allocate(layout).unwrap_or_else(|_| handle_alloc_error(layout)); - - // Initialize the ArcInner - let inner = mem_to_arcinner(ptr.as_non_null_ptr().as_ptr()); - debug_assert_eq!(unsafe { Layout::for_value(&*inner) }, layout); - unsafe { - ptr::write(&mut (*inner).strong, atomic::AtomicUsize::new(1)); - ptr::write(&mut (*inner).weak, atomic::AtomicUsize::new(1)); + Arc::try_allocate_for_layout(value_layout, allocate, mem_to_arcinner) + .unwrap_or_else(|_| handle_alloc_error(layout)) } - - inner } /// Allocates an `ArcInner` with sufficient space for