From 2633b85ab2c89822d2c227fc9e81c6ec1c0ed9b6 Mon Sep 17 00:00:00 2001 From: Ixrec Date: Sun, 17 Sep 2017 17:03:56 +0100 Subject: [PATCH 1/2] Replace str's transmute() calls with pointer casts After the following conversation in #rust-lang: ``` [14:43:50] TIL the implementation of from_utf_unchecked is literally just "mem::transmute(x)" [14:43:59] no wonder people keep saying transmute is overpowered [15:15:30] Ixrec: it should be a pointer cast lol [15:15:46] unless it doesn't let you [16:50:34] https://play.rust-lang.org/?gist=d1e6b629ad9ec1baf64ce261c63845e6&version=stable seems like it does let me [16:52:35] Ixrec: yeah that's the preferred impl [16:52:46] Ixrec: it just wasn't in 1.0 [16:52:50] IIRC [16:53:00] (something something fat pointers) ``` Since I already wrote half of the preferred impls in the playground, might as well make an actual PR. --- src/libcore/str/mod.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index d4fef45ae4e8f..60f3640446cab 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -404,7 +404,7 @@ unsafe fn from_raw_parts_mut<'a>(p: *mut u8, len: usize) -> &'a mut str { #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str { - mem::transmute(v) + &*(v as *const [u8] as *const str) } /// Converts a slice of bytes to a string slice without checking @@ -429,7 +429,7 @@ pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str { #[inline] #[stable(feature = "str_mut_extras", since = "1.20.0")] pub unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str { - mem::transmute(v) + &*(v as *mut [u8] as *mut str) } #[stable(feature = "rust1", since = "1.0.0")] @@ -2447,12 +2447,12 @@ impl StrExt for str { #[inline] fn as_bytes(&self) -> &[u8] { - unsafe { mem::transmute(self) } + unsafe { &*(self as *const str as *const [u8]) } } #[inline] unsafe fn as_bytes_mut(&mut self) -> &mut [u8] { - mem::transmute(self) + &mut *(self as *mut str as *mut [u8]) } fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option { From 38fa340ba263612a6f7351d4800d6d4f57ac1cdf Mon Sep 17 00:00:00 2001 From: Ixrec Date: Sun, 17 Sep 2017 17:11:42 +0100 Subject: [PATCH 2/2] missed a 'mut' --- src/libcore/str/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index 60f3640446cab..862085c7228af 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -429,7 +429,7 @@ pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str { #[inline] #[stable(feature = "str_mut_extras", since = "1.20.0")] pub unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str { - &*(v as *mut [u8] as *mut str) + &mut *(v as *mut [u8] as *mut str) } #[stable(feature = "rust1", since = "1.0.0")]