From 0550c2117480d4e2dd4b7b58c7ac3784f6938e36 Mon Sep 17 00:00:00 2001 From: Gaelan Steele Date: Mon, 21 Dec 2020 01:26:29 -0800 Subject: [PATCH 1/2] Use TryInto to avoid unsafe. Previously, to_fields and to_fields_le used unsafe to convert a &[u8] into a &[u8; 8]. Now that we're only supporting Rust versions where TryInto is stable, we can use try_into().unwrap() instead, making uuid entirely safe Rust. In release mode, the compiler detects that the slice will always be the correct size, so try_into can never fail. Thus, the unwrap is optimized out and we end up with the exact same assembly as the unsafe block. Godbolt output showing the resulting assembly: https://godbolt.org/z/nWxT6W Closes #488. --- src/lib.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index fe57353f8..c18ea949d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -198,7 +198,7 @@ mod v5; #[cfg(all(windows, feature = "winapi"))] mod winapi_support; -use crate::std::{fmt, str}; +use crate::std::{convert::TryInto, fmt, str}; pub use crate::error::Error; @@ -390,8 +390,7 @@ impl Uuid { let d3 = u16::from(self.as_bytes()[6]) << 8 | u16::from(self.as_bytes()[7]); - let d4: &[u8; 8] = - unsafe { &*(self.as_bytes()[8..16].as_ptr() as *const [u8; 8]) }; + let d4: &[u8; 8] = self.as_bytes()[8..16].try_into().unwrap(); (d1, d2, d3, d4) } @@ -431,8 +430,7 @@ impl Uuid { let d3 = u16::from(self.as_bytes()[6]) | u16::from(self.as_bytes()[7]) << 8; - let d4: &[u8; 8] = - unsafe { &*(self.as_bytes()[8..16].as_ptr() as *const [u8; 8]) }; + let d4: &[u8; 8] = self.as_bytes()[8..16].try_into().unwrap(); (d1, d2, d3, d4) } From f93a2ada47c1392aa81a1ad41ec5011280423bb5 Mon Sep 17 00:00:00 2001 From: Gaelan Steele Date: Mon, 4 Jan 2021 13:56:27 -0800 Subject: [PATCH 2/2] Remove TryFrom import. --- src/lib.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index c18ea949d..c77dad634 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -198,7 +198,7 @@ mod v5; #[cfg(all(windows, feature = "winapi"))] mod winapi_support; -use crate::std::{convert::TryInto, fmt, str}; +use crate::std::{convert, fmt, str}; pub use crate::error::Error; @@ -390,7 +390,8 @@ impl Uuid { let d3 = u16::from(self.as_bytes()[6]) << 8 | u16::from(self.as_bytes()[7]); - let d4: &[u8; 8] = self.as_bytes()[8..16].try_into().unwrap(); + let d4: &[u8; 8] = + convert::TryInto::try_into(&self.as_bytes()[8..16]).unwrap(); (d1, d2, d3, d4) } @@ -430,7 +431,8 @@ impl Uuid { let d3 = u16::from(self.as_bytes()[6]) | u16::from(self.as_bytes()[7]) << 8; - let d4: &[u8; 8] = self.as_bytes()[8..16].try_into().unwrap(); + let d4: &[u8; 8] = + convert::TryInto::try_into(&self.as_bytes()[8..16]).unwrap(); (d1, d2, d3, d4) }