Add a cast method to raw pointers.

This is similar to `NonNull::cast`.

Compared to the `as` operator (which has a wide range of meanings
depending on the input and output types), a call to this method:

* Can only go from a raw pointer to a raw pointer
* Cannot change the pointer’s `const`ness

… even when the pointed types are inferred based on context.
This commit is contained in:
Simon Sapin 2019-05-07 13:32:07 +02:00
parent a19cf18c7d
commit d5e819015f

View file

@ -974,6 +974,13 @@ impl<T: ?Sized> *const T {
(self as *const u8) == null()
}
/// Cast to a pointer to a different type
#[unstable(feature = "ptr_cast", issue = "60602")]
#[inline]
pub const fn cast<U>(self) -> *const U {
self as _
}
/// Returns `None` if the pointer is null, or else returns a reference to
/// the value wrapped in `Some`.
///
@ -1593,6 +1600,13 @@ impl<T: ?Sized> *mut T {
(self as *mut u8) == null_mut()
}
/// Cast to a pointer to a different type
#[unstable(feature = "ptr_cast", issue = "60602")]
#[inline]
pub const fn cast<U>(self) -> *mut U {
self as _
}
/// Returns `None` if the pointer is null, or else returns a reference to
/// the value wrapped in `Some`.
///