File tree Expand file tree Collapse file tree 1 file changed +12
-11
lines changed Expand file tree Collapse file tree 1 file changed +12
-11
lines changed Original file line number Diff line number Diff line change @@ -1841,17 +1841,18 @@ impl<T> Weak<T> {
1841
1841
/// [`new`]: Weak::new
1842
1842
#[ stable( feature = "weak_into_raw" , since = "1.45.0" ) ]
1843
1843
pub unsafe fn from_raw ( ptr : * const T ) -> Self {
1844
- if ptr. is_null ( ) {
1845
- Self :: new ( )
1846
- } else {
1847
- // See Rc::from_raw for details
1848
- unsafe {
1849
- let offset = data_offset ( ptr) ;
1850
- let fake_ptr = ptr as * mut RcBox < T > ;
1851
- let ptr = set_data_ptr ( fake_ptr, ( ptr as * mut u8 ) . offset ( -offset) ) ;
1852
- Weak { ptr : NonNull :: new ( ptr) . expect ( "Invalid pointer passed to from_raw" ) }
1853
- }
1854
- }
1844
+ // SAFETY: data_offset is safe to call, because this pointer originates from a Weak.
1845
+ // See Weak::as_ptr for context on how the input pointer is derived.
1846
+ let offset = unsafe { data_offset ( ptr) } ;
1847
+
1848
+ // Reverse the offset to find the original RcBox.
1849
+ // SAFETY: we use wrapping_offset here because the pointer may be dangling (iff T: Sized).
1850
+ let ptr = unsafe {
1851
+ set_data_ptr ( ptr as * mut RcBox < T > , ( ptr as * mut u8 ) . wrapping_offset ( -offset) )
1852
+ } ;
1853
+
1854
+ // SAFETY: we now have recovered the original Weak pointer, so can create the Weak.
1855
+ Weak { ptr : unsafe { NonNull :: new_unchecked ( ptr) } }
1855
1856
}
1856
1857
}
1857
1858
You can’t perform that action at this time.
0 commit comments