Skip to content

Commit

Permalink
Rollup merge of rust-lang#130046 - RalfJung:const_str_as_mut, r=dtolnay
Browse files Browse the repository at this point in the history
str: make as_mut_ptr and as_bytes_mut unstably const

`@rust-lang/libs-api` the corresponding non-mutable methods are already const fn, so this seems pretty trivial. I hope this is small enough that it does not need an ACP? :)

I would like to get these stabilized ASAP because I want to avoid people doing `s.as_ptr().cast_mut()`, which is UB if they ever write to it, but is already const-stable.

TODO: create a tracking issue.
  • Loading branch information
matthiaskrgr authored Sep 7, 2024
2 parents 2feca1e + 3a53537 commit 9448662
Showing 1 changed file with 4 additions and 2 deletions.
6 changes: 4 additions & 2 deletions core/src/str/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -338,9 +338,10 @@ impl str {
/// assert_eq!("🍔∈🌏", s);
/// ```
#[stable(feature = "str_mut_extras", since = "1.20.0")]
#[rustc_const_unstable(feature = "const_str_as_mut", issue = "130086")]
#[must_use]
#[inline(always)]
pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
pub const unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
// SAFETY: the cast from `&str` to `&[u8]` is safe since `str`
// has the same layout as `&[u8]` (only std can make this guarantee).
// The pointer dereference is safe since it comes from a mutable reference which
Expand Down Expand Up @@ -383,10 +384,11 @@ impl str {
/// It is your responsibility to make sure that the string slice only gets
/// modified in a way that it remains valid UTF-8.
#[stable(feature = "str_as_mut_ptr", since = "1.36.0")]
#[rustc_const_unstable(feature = "const_str_as_mut", issue = "130086")]
#[rustc_never_returns_null_ptr]
#[must_use]
#[inline(always)]
pub fn as_mut_ptr(&mut self) -> *mut u8 {
pub const fn as_mut_ptr(&mut self) -> *mut u8 {
self as *mut str as *mut u8
}

Expand Down

0 comments on commit 9448662

Please sign in to comment.