Skip to content

Commit 0c7bf56

Browse files
committed
Update Arc and Rc to use NonNull::cast to cast the inner pointers
This avoids an `unsafe` block in each case.
1 parent 37f5cf5 commit 0c7bf56

File tree

2 files changed

+6
-17
lines changed

2 files changed

+6
-17
lines changed

Diff for: src/liballoc/arc.rs

+3-8
Original file line numberDiff line numberDiff line change
@@ -1001,14 +1001,9 @@ impl Arc<Any + Send + Sync> {
10011001
T: Any + Send + Sync + 'static,
10021002
{
10031003
if (*self).is::<T>() {
1004-
unsafe {
1005-
let raw: *const ArcInner<Any + Send + Sync> = self.ptr.as_ptr();
1006-
mem::forget(self);
1007-
Ok(Arc {
1008-
ptr: NonNull::new_unchecked(raw as *const ArcInner<T> as *mut _),
1009-
phantom: PhantomData,
1010-
})
1011-
}
1004+
let ptr = self.ptr.cast::<ArcInner<T>>();
1005+
mem::forget(self);
1006+
Ok(Arc { ptr, phantom: PhantomData })
10121007
} else {
10131008
Err(self)
10141009
}

Diff for: src/liballoc/rc.rs

+3-9
Original file line numberDiff line numberDiff line change
@@ -644,15 +644,9 @@ impl Rc<Any> {
644644
/// ```
645645
pub fn downcast<T: Any>(self) -> Result<Rc<T>, Rc<Any>> {
646646
if (*self).is::<T>() {
647-
// avoid the pointer arithmetic in from_raw
648-
unsafe {
649-
let raw: *const RcBox<Any> = self.ptr.as_ptr();
650-
forget(self);
651-
Ok(Rc {
652-
ptr: NonNull::new_unchecked(raw as *const RcBox<T> as *mut _),
653-
phantom: PhantomData,
654-
})
655-
}
647+
let ptr = self.ptr.cast::<RcBox<T>>();
648+
forget(self);
649+
Ok(Rc { ptr, phantom: PhantomData })
656650
} else {
657651
Err(self)
658652
}

0 commit comments

Comments
 (0)