From 939d2230d293a7bb939d8760d1fd74af76da8e18 Mon Sep 17 00:00:00 2001 From: junderw Date: Sun, 25 Jun 2023 00:44:08 -0700 Subject: [PATCH] Use bytemuck instead of unsafe Rust --- Cargo.lock | 7 +++++++ backend/rust-gbt/Cargo.toml | 1 + backend/rust-gbt/src/u32_hashmap.rs | 8 ++++---- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7837483d7..16fdc9c54 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -23,6 +23,12 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbe3c979c178231552ecba20214a8272df4e09f232a87aef4320cf06539aded" +[[package]] +name = "bytemuck" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17febce684fd15d89027105661fec94afb475cb995fbc59d2865198446ba2eea" + [[package]] name = "bytes" version = "1.4.0" @@ -58,6 +64,7 @@ dependencies = [ name = "gbt" version = "0.1.0" dependencies = [ + "bytemuck", "bytes", "napi", "napi-build", diff --git a/backend/rust-gbt/Cargo.toml b/backend/rust-gbt/Cargo.toml index a0f593518..2585a09e6 100644 --- a/backend/rust-gbt/Cargo.toml +++ b/backend/rust-gbt/Cargo.toml @@ -17,6 +17,7 @@ bytes = "1.4.0" once_cell = "1.18.0" napi = { version = "2.13.2", features = ["napi8", "tokio_rt"] } napi-derive = "2.13.0" +bytemuck = "1.13.1" [build-dependencies] napi-build = "2.0.1" diff --git a/backend/rust-gbt/src/u32_hashmap.rs b/backend/rust-gbt/src/u32_hashmap.rs index 26ab38718..cfa513301 100644 --- a/backend/rust-gbt/src/u32_hashmap.rs +++ b/backend/rust-gbt/src/u32_hashmap.rs @@ -31,16 +31,16 @@ pub struct U32Hasher(u32); impl Hasher for U32Hasher { fn finish(&self) -> u64 { // Safety: Two u32s next to each other will make a u64 - unsafe { core::mem::transmute::<(u32, u32), u64>((self.0, 0_u32)) } + bytemuck::cast([self.0, 0]) } fn write(&mut self, bytes: &[u8]) { // Assert in debug builds (testing too) that only 4 byte keys (u32, i32, f32, etc.) run debug_assert!(bytes.len() == 4); - // Safety: We know that the size of the key is at least 4 bytes + // Safety: We know that the size of the key is 4 bytes // We also know that the only way to get an instance of HashMap using this "hasher" - // is through the public functions in this module which set the key to u32. - self.0 = unsafe { *bytes.as_ptr().cast::() }; + // is through the public functions in this module which set the key type to u32. + self.0 = *bytemuck::from_bytes(bytes); } }