From baae210ed248b668991d6ade1916c478152804f0 Mon Sep 17 00:00:00 2001 From: Gaelan Steele Date: Mon, 21 Dec 2020 01:26:29 -0800 Subject: [PATCH] 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..5a2f3831c 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::{fmt, str, convert::TryInto}; 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) }