Skip to content

Commit

Permalink
Rollup merge of #92657 - Kixunil:ptr_as_const_mut, r=m-ou-se
Browse files Browse the repository at this point in the history
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
  • Loading branch information
matthiaskrgr authored Jan 9, 2022
2 parents 51001b3 + 1a96623 commit 295ef3a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
10 changes: 10 additions & 0 deletions library/core/src/ptr/const_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,16 @@ impl<T: ?Sized> *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.
Expand Down
14 changes: 14 additions & 0 deletions library/core/src/ptr/mut_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,20 @@ impl<T: ?Sized> *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.
Expand Down

0 comments on commit 295ef3a

Please sign in to comment.