Skip to content

Commit 346dc37

Browse files
committed
fix str mutating through a ptr derived from &self
1 parent d30b99f commit 346dc37

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

src/libcore/str/mod.rs

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1757,7 +1757,7 @@ mod traits {
17571757
}
17581758
#[inline]
17591759
unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1760-
let ptr = slice.as_ptr().add(self.start);
1760+
let ptr = slice.as_mut_ptr().add(self.start);
17611761
let len = self.end - self.start;
17621762
super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, len))
17631763
}
@@ -1821,7 +1821,7 @@ mod traits {
18211821
}
18221822
#[inline]
18231823
unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1824-
let ptr = slice.as_ptr();
1824+
let ptr = slice.as_mut_ptr();
18251825
super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, self.end))
18261826
}
18271827
#[inline]
@@ -1883,7 +1883,7 @@ mod traits {
18831883
}
18841884
#[inline]
18851885
unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output {
1886-
let ptr = slice.as_ptr().add(self.start);
1886+
let ptr = slice.as_mut_ptr().add(self.start);
18871887
let len = slice.len() - self.start;
18881888
super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr as *mut u8, len))
18891889
}
@@ -2213,6 +2213,22 @@ impl str {
22132213
self as *const str as *const u8
22142214
}
22152215

2216+
/// Converts a mutable string slice to a raw pointer.
2217+
///
2218+
/// As string slices are a slice of bytes, the raw pointer points to a
2219+
/// [`u8`]. This pointer will be pointing to the first byte of the string
2220+
/// slice.
2221+
///
2222+
/// It is your responsibility to make sure that the string slice only gets
2223+
/// modified in a way that it remains valid UTF-8.
2224+
///
2225+
/// [`u8`]: primitive.u8.html
2226+
#[unstable(feature = "str_as_mut_ptr", issue = "0")]
2227+
#[inline]
2228+
pub fn as_mut_ptr(&mut self) -> *mut u8 {
2229+
self as *mut str as *mut u8
2230+
}
2231+
22162232
/// Returns a subslice of `str`.
22172233
///
22182234
/// This is the non-panicking alternative to indexing the `str`. Returns

0 commit comments

Comments
 (0)