1
Fork 0

Refactor set_ptr_value as with_metadata_of

By reversing the arguments we achieve several clarifications:

- The function closely resembles `cast` but with an argument to
  initialized the metadata. This is easier to teach and answers an long
  outstanding question that had restricted cast to `Sized` targets
  initially. See multiples reviews of
  <https://github.com/rust-lang/rust/pull/47631>
- The 'object identity', in the form or provenance, is now preserved
  from the call receiver to the result. This helps explain the method as
  a builder-style, instead of some kind of setter that would modify
  something in-place. Ensuring that the result has the identity of the
  `self` argument is also beneficial for an intuition of effects.
- An outstanding concern, 'Correct argument type', is avoided by not
  committing to any specific argument type. This is consistent with cast
  which does not require its receiver to be a raw address.
This commit is contained in:
Andreas Molzer 2022-03-12 00:21:35 +01:00
parent c9b45e6010
commit d489ea777d
4 changed files with 95 additions and 88 deletions

View file

@ -895,7 +895,7 @@ impl<T: ?Sized> Rc<T> {
// Reverse the offset to find the original RcBox.
let rc_ptr =
unsafe { (ptr as *mut RcBox<T>).set_ptr_value((ptr as *mut u8).offset(-offset)) };
unsafe { (ptr as *mut u8).offset(-offset).with_metadata_of(ptr as *mut RcBox<T>) };
unsafe { Self::from_ptr(rc_ptr) }
}
@ -1338,7 +1338,7 @@ impl<T: ?Sized> Rc<T> {
Self::allocate_for_layout(
Layout::for_value(&*ptr),
|layout| Global.allocate(layout),
|mem| (ptr as *mut RcBox<T>).set_ptr_value(mem),
|mem| mem.with_metadata_of(ptr as *mut RcBox<T>),
)
}
}
@ -2263,7 +2263,7 @@ impl<T: ?Sized> Weak<T> {
let offset = unsafe { data_offset(ptr) };
// Thus, we reverse the offset to get the whole RcBox.
// SAFETY: the pointer originated from a Weak, so this offset is safe.
unsafe { (ptr as *mut RcBox<T>).set_ptr_value((ptr as *mut u8).offset(-offset)) }
unsafe { (ptr as *mut u8).offset(-offset).with_metadata_of(ptr as *mut RcBox<T>) }
};
// SAFETY: we now have recovered the original Weak pointer, so can create the Weak.