Feature gate: #![feature(as_ref_unchecked)] (or similar)
This is a tracking issue for raw-pointer-to-reference conversion methods (rust-lang/libs-team#342).
With #106116, we have methods for almost all casts/conversions one wants to do on references and pointers, to avoid as casts and prefix operators. Just one direction is missing: turning raw pointers into references. Here we have as_ref/as_mut, but they behave different from &*ptr/&mut *ptr: they return an Option and perform a null-check. (These are the only methods on raw pointers that perform a null check.)
Public API
impl<T> *const T {
unsafe const fn as_ref_unchecked<'a>(self) -> &'a T {
&*self
}
}
impl<T> *mut T {
unsafe const fn as_ref_unchecked<'a>(self) -> &'a T {
&*self
}
unsafe const fn as_mut_unchecked<'a>(self) -> &'a mut T {
&mut *self
}
}
Motivating examples or use cases
Some random examples from a quick grep of the rustc sources:
&mut *(out as *mut &mut dyn PrintBackendInfo)
&mut *(state as *mut &mut dyn FnMut(&[u8]) -> io::Result<()>)
&mut *(self.0 as *mut _)
&mut *(vec as *mut Vec<Library>)
&mut *(value as *mut T as *mut UnsafeCell<T>)
&mut *(s as *mut T).cast::<[T; 1]>()
The examples above then become
out.cast::<&mut dyn PrintBackendInfo>().as_mut_unchecked()
state.cast::<&mut dyn FnMut(&[u8]) -> io::Result<()>>().as_mut_unchecked()
self.0.cast().as_mut_unchecked()
vec.cast::<Vec<Library>>().as_mut_unchecked()
ptr::from_mut(value).cast::<UnsafeCell<T>>().as_mut_unchecked()
ptr::from_mut(s).cast::<[T; 1]>().as_mut_unchecked()
Unfortunately, since the as_mut name is already taken, these are all longer than the prefix variants. But they can be read left-to-right which is an advantage.
Steps / History
Unresolved Questions
- Is there a shorter name we could use?
Feature gate:
#This is a tracking issue for raw-pointer-to-reference conversion methods (rust-lang/libs-team#342).
With #106116, we have methods for almost all casts/conversions one wants to do on references and pointers, to avoid
ascasts and prefix operators. Just one direction is missing: turning raw pointers into references. Here we haveas_ref/as_mut, but they behave different from&*ptr/&mut *ptr: they return anOptionand perform a null-check. (These are the only methods on raw pointers that perform a null check.)Public API
Motivating examples or use cases
Some random examples from a quick grep of the rustc sources:
The examples above then become
Unfortunately, since the
as_mutname is already taken, these are all longer than the prefix variants. But they can be read left-to-right which is an advantage.Steps / History
Unresolved Questions
Footnotes
https://std-dev-guide.rust-lang.org/feature-lifecycle/stabilization.html ↩