Skip to content

Commit 295ef3a

Browse files
authored
Rollup merge of #92657 - Kixunil:ptr_as_const_mut, r=m-ou-se
Implemented const casts of raw pointers This adds `as_mut()` method for `*const T` and `as_const()` for `*mut T` which are intended to make casting of consts safer. This was discussed in the [internals discussion][discussion]. Given that this is a simple change and multiple people agreed to it including `@RalfJung` I decided to go ahead and open the PR. [discussion]: https://internals.rust-lang.org/t/casting-constness-can-be-risky-heres-a-simple-fix/15933
2 parents 51001b3 + 1a96623 commit 295ef3a

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

library/core/src/ptr/const_ptr.rs

+10
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,16 @@ impl<T: ?Sized> *const T {
4848
self as _
4949
}
5050

51+
/// Changes constness without changing the type.
52+
///
53+
/// This is a bit safer than `as` because it wouldn't silently change the type if the code is
54+
/// refactored.
55+
#[unstable(feature = "ptr_const_cast", issue = "92675")]
56+
#[rustc_const_unstable(feature = "ptr_const_cast", issue = "92675")]
57+
pub const fn as_mut(self) -> *mut T {
58+
self as _
59+
}
60+
5161
/// Casts a pointer to its raw bits.
5262
///
5363
/// This is equivalent to `as usize`, but is more specific to enhance readability.

library/core/src/ptr/mut_ptr.rs

+14
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,20 @@ impl<T: ?Sized> *mut T {
4747
self as _
4848
}
4949

50+
/// Changes constness without changing the type.
51+
///
52+
/// This is a bit safer than `as` because it wouldn't silently change the type if the code is
53+
/// refactored.
54+
///
55+
/// While not strictly required (`*mut T` coerces to `*const T`), this is provided for symmetry
56+
/// with `as_mut()` on `*const T` and may have documentation value if used instead of implicit
57+
/// coercion.
58+
#[unstable(feature = "ptr_const_cast", issue = "92675")]
59+
#[rustc_const_unstable(feature = "ptr_const_cast", issue = "92675")]
60+
pub const fn as_const(self) -> *const T {
61+
self as _
62+
}
63+
5064
/// Casts a pointer to its raw bits.
5165
///
5266
/// This is equivalent to `as usize`, but is more specific to enhance readability.

0 commit comments

Comments
 (0)