Skip to content

Commit 97990cd

Browse files
authored
Rollup merge of #44657 - Ixrec:patch-1, r=eddyb
Replace str's transmute() calls with pointer casts After the following conversation in #rust-lang: ``` [14:43:50] <Ixrec> TIL the implementation of from_utf_unchecked is literally just "mem::transmute(x)" [14:43:59] <Ixrec> no wonder people keep saying transmute is overpowered [15:15:30] <eddyb> Ixrec: it should be a pointer cast lol [15:15:46] <eddyb> unless it doesn't let you [16:50:34] <Ixrec> https://play.rust-lang.org/?gist=d1e6b629ad9ec1baf64ce261c63845e6&version=stable seems like it does let me [16:52:35] <eddyb> Ixrec: yeah that's the preferred impl [16:52:46] <eddyb> Ixrec: it just wasn't in 1.0 [16:52:50] <eddyb> IIRC [16:53:00] <eddyb> (something something fat pointers) ``` Since I already wrote half of the preferred impls in the playground, might as well make an actual PR.
2 parents fba954b + 38fa340 commit 97990cd

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

src/libcore/str/mod.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -403,7 +403,7 @@ unsafe fn from_raw_parts_mut<'a>(p: *mut u8, len: usize) -> &'a mut str {
403403
#[inline]
404404
#[stable(feature = "rust1", since = "1.0.0")]
405405
pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
406-
mem::transmute(v)
406+
&*(v as *const [u8] as *const str)
407407
}
408408

409409
/// Converts a slice of bytes to a string slice without checking
@@ -428,7 +428,7 @@ pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
428428
#[inline]
429429
#[stable(feature = "str_mut_extras", since = "1.20.0")]
430430
pub unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {
431-
mem::transmute(v)
431+
&mut *(v as *mut [u8] as *mut str)
432432
}
433433

434434
#[stable(feature = "rust1", since = "1.0.0")]
@@ -2446,12 +2446,12 @@ impl StrExt for str {
24462446

24472447
#[inline]
24482448
fn as_bytes(&self) -> &[u8] {
2449-
unsafe { mem::transmute(self) }
2449+
unsafe { &*(self as *const str as *const [u8]) }
24502450
}
24512451

24522452
#[inline]
24532453
unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
2454-
mem::transmute(self)
2454+
&mut *(self as *mut str as *mut [u8])
24552455
}
24562456

24572457
fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {

0 commit comments

Comments
 (0)