From 1a966235138ad68967aa0892aa0621315081e4e8 Mon Sep 17 00:00:00 2001 From: Martin Habovstiak Date: Sat, 8 Jan 2022 00:03:02 +0100 Subject: [PATCH] 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]. [discussion]: https://internals.rust-lang.org/t/casting-constness-can-be-risky-heres-a-simple-fix/15933 --- library/core/src/ptr/const_ptr.rs | 10 ++++++++++ library/core/src/ptr/mut_ptr.rs | 14 ++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/library/core/src/ptr/const_ptr.rs b/library/core/src/ptr/const_ptr.rs index a93327a0132ed..7b826f921ca87 100644 --- a/library/core/src/ptr/const_ptr.rs +++ b/library/core/src/ptr/const_ptr.rs @@ -48,6 +48,16 @@ impl *const T { self as _ } + /// Changes constness without changing the type. + /// + /// This is a bit safer than `as` because it wouldn't silently change the type if the code is + /// refactored. + #[unstable(feature = "ptr_const_cast", issue = "92675")] + #[rustc_const_unstable(feature = "ptr_const_cast", issue = "92675")] + pub const fn as_mut(self) -> *mut T { + self as _ + } + /// Casts a pointer to its raw bits. /// /// This is equivalent to `as usize`, but is more specific to enhance readability. diff --git a/library/core/src/ptr/mut_ptr.rs b/library/core/src/ptr/mut_ptr.rs index 5fd3b2ebc6098..6c50d4052976f 100644 --- a/library/core/src/ptr/mut_ptr.rs +++ b/library/core/src/ptr/mut_ptr.rs @@ -47,6 +47,20 @@ impl *mut T { self as _ } + /// Changes constness without changing the type. + /// + /// This is a bit safer than `as` because it wouldn't silently change the type if the code is + /// refactored. + /// + /// While not strictly required (`*mut T` coerces to `*const T`), this is provided for symmetry + /// with `as_mut()` on `*const T` and may have documentation value if used instead of implicit + /// coercion. + #[unstable(feature = "ptr_const_cast", issue = "92675")] + #[rustc_const_unstable(feature = "ptr_const_cast", issue = "92675")] + pub const fn as_const(self) -> *const T { + self as _ + } + /// Casts a pointer to its raw bits. /// /// This is equivalent to `as usize`, but is more specific to enhance readability.