Skip to content

Commit 0cf9503

Browse files
committed
Replace pointer casting in hashmap_random_keys with safe code
The old code was unnecessarily unsafe and relied on the layout of tuples always being the same as an array of the same size.
1 parent f03ce30 commit 0cf9503

File tree

1 file changed

+9
-9
lines changed

1 file changed

+9
-9
lines changed

library/std/src/sys/unix/rand.rs

+9-9
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1-
use crate::mem;
2-
use crate::slice;
3-
41
pub fn hashmap_random_keys() -> (u64, u64) {
5-
let mut v = (0, 0);
6-
unsafe {
7-
let view = slice::from_raw_parts_mut(&mut v as *mut _ as *mut u8, mem::size_of_val(&v));
8-
imp::fill_bytes(view);
9-
}
10-
v
2+
const KEY_LEN: usize = core::mem::size_of::<u64>();
3+
4+
let mut v = [0u8; KEY_LEN * 2];
5+
imp::fill_bytes(&mut v);
6+
7+
let key1 = v[0..KEY_LEN].try_into().unwrap();
8+
let key2 = v[KEY_LEN..].try_into().unwrap();
9+
10+
(u64::from_ne_bytes(key1), u64::from_ne_bytes(key2))
1111
}
1212

1313
#[cfg(all(

0 commit comments

Comments
 (0)