Skip to content

Commit

Permalink
Make [A]Rc::allocate_for_layout() use try_allocate_for_layout()
Browse files Browse the repository at this point in the history
  • Loading branch information
Manishearth committed Dec 31, 2020
1 parent 589aa8e commit 8f3cb7d
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 23 deletions.
15 changes: 3 additions & 12 deletions library/alloc/src/rc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1107,20 +1107,10 @@ impl<T: ?Sized> Rc<T> {
// `&*(ptr as *const RcBox<T>)`, but this created a misaligned
// reference (see #54908).
let layout = Layout::new::<RcBox<()>>().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<T>` with sufficient space for
Expand All @@ -1129,6 +1119,7 @@ impl<T: ?Sized> Rc<T> {
///
/// The function `mem_to_rcbox` is called with the data pointer
/// and must return back a (potentially fat)-pointer for the `RcBox<T>`.
#[inline]
unsafe fn try_allocate_for_layout(
value_layout: Layout,
allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>,
Expand Down
13 changes: 2 additions & 11 deletions library/alloc/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1085,19 +1085,10 @@ impl<T: ?Sized> Arc<T> {
// `&*(ptr as *const ArcInner<T>)`, but this created a misaligned
// reference (see #54908).
let layout = Layout::new::<ArcInner<()>>().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<T>` with sufficient space for
Expand Down

0 comments on commit 8f3cb7d

Please sign in to comment.