Skip to content

Commit

Permalink
Rc destructor: tweak inlining
Browse files Browse the repository at this point in the history
  • Loading branch information
Lukas Markeffsky committed Oct 28, 2024
1 parent 28223bd commit 9318ae3
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions alloc/src/rc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,21 @@ impl<T: ?Sized, A: Allocator> Rc<T, A> {
unsafe fn from_ptr_in(ptr: *mut RcInner<T>, alloc: A) -> Self {
unsafe { Self::from_inner_in(NonNull::new_unchecked(ptr), alloc) }
}

// Non-inlined part of `drop`.
#[inline(never)]
unsafe fn drop_slow(&mut self) {
// Reconstruct the "strong weak" pointer and drop it when this
// variable goes out of scope. This ensures that the memory is
// deallocated even if the destructor of `T` panics.
let _weak = Weak { ptr: self.ptr, alloc: &self.alloc };

// Destroy the contained object.
// We cannot use `get_mut_unchecked` here, because `self.alloc` is borrowed.
unsafe {
ptr::drop_in_place(&mut (*self.ptr.as_ptr()).value);
}
}
}

impl<T> Rc<T> {
Expand Down Expand Up @@ -2252,18 +2267,12 @@ unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Rc<T, A> {
/// drop(foo); // Doesn't print anything
/// drop(foo2); // Prints "dropped!"
/// ```
#[inline]
fn drop(&mut self) {
unsafe {
self.inner().dec_strong();
if self.inner().strong() == 0 {
// Reconstruct the "strong weak" pointer and drop it when this
// variable goes out of scope. This ensures that the memory is
// deallocated even if the destructor of `T` panics.
let _weak = Weak { ptr: self.ptr, alloc: &self.alloc };

// Destroy the contained object.
// We cannot use `get_mut_unchecked` here, because `self.alloc` is borrowed.
ptr::drop_in_place(&mut (*self.ptr.as_ptr()).value);
self.drop_slow();
}
}
}
Expand Down

0 comments on commit 9318ae3

Please sign in to comment.