1
Fork 0

Rollup merge of #130046 - RalfJung:const_str_as_mut, r=dtolnay

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.
This commit is contained in:
Matthias Krüger 2024-09-07 23:30:14 +02:00 committed by GitHub
commit c139dc6281
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -338,9 +338,10 @@ impl str {
/// assert_eq!("🍔∈🌏", s); /// assert_eq!("🍔∈🌏", s);
/// ``` /// ```
#[stable(feature = "str_mut_extras", since = "1.20.0")] #[stable(feature = "str_mut_extras", since = "1.20.0")]
#[rustc_const_unstable(feature = "const_str_as_mut", issue = "130086")]
#[must_use] #[must_use]
#[inline(always)] #[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` // SAFETY: the cast from `&str` to `&[u8]` is safe since `str`
// has the same layout as `&[u8]` (only std can make this guarantee). // 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 // The pointer dereference is safe since it comes from a mutable reference which
@ -383,10 +384,11 @@ impl str {
/// It is your responsibility to make sure that the string slice only gets /// It is your responsibility to make sure that the string slice only gets
/// modified in a way that it remains valid UTF-8. /// modified in a way that it remains valid UTF-8.
#[stable(feature = "str_as_mut_ptr", since = "1.36.0")] #[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] #[rustc_never_returns_null_ptr]
#[must_use] #[must_use]
#[inline(always)] #[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 self as *mut str as *mut u8
} }