Skip to content

Commit

Permalink
Merge #507
Browse files Browse the repository at this point in the history
507: Use TryInto to avoid unsafe. r=kinggoesgaming a=Gaelan

<!--
    If this PR is a breaking change, ensure that you are opening it against 
    the `breaking` branch.  If the pull request is incomplete, prepend the Title with WIP: 
-->

**I'm submitting a(n)** refactor

# Description

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

# Motivation

Makes UUID entirely safe Rust.

With this PR,

# Tests

All existing tests pass. Doesn't add any new functionality, so that should be sufficient. Assuming the Godbolt test is consistent with what happens in the context of the larger crate, this shouldn't change the resulting binary at all.

# Related Issue(s)

Closes #488.


Co-authored-by: Gaelan Steele <gbs@canishe.com>
  • Loading branch information
bors[bot] and Gaelan authored Jan 17, 2021
2 parents 54d7bec + f93a2ad commit 805f4ed
Showing 1 changed file with 3 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ mod v5;
#[cfg(all(windows, feature = "winapi"))]
mod winapi_support;

use crate::std::{fmt, str};
use crate::std::{convert, fmt, str};

pub use crate::error::Error;

Expand Down Expand Up @@ -388,7 +388,7 @@ impl Uuid {
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]) };
convert::TryInto::try_into(&self.as_bytes()[8..16]).unwrap();
(d1, d2, d3, d4)
}

Expand Down Expand Up @@ -429,7 +429,7 @@ impl Uuid {
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]) };
convert::TryInto::try_into(&self.as_bytes()[8..16]).unwrap();
(d1, d2, d3, d4)
}

Expand Down

0 comments on commit 805f4ed

Please sign in to comment.