Use bytemuck instead of unsafe Rust

This commit is contained in:
junderw 2023-06-25 00:44:08 -07:00 committed by Mononaut
parent 59b19eefe3
commit 939d2230d2
No known key found for this signature in database
GPG Key ID: A3F058E41374C04E
3 changed files with 12 additions and 4 deletions

7
Cargo.lock generated
View File

@ -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",

View File

@ -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"

View File

@ -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::<u32>() };
// is through the public functions in this module which set the key type to u32.
self.0 = *bytemuck::from_bytes(bytes);
}
}