Skip to content

Commit

Permalink
Auto merge of rust-lang#100298 - BlackHoleFox:hashmap_keygen_cleanup,…
Browse files Browse the repository at this point in the history
… r=Mark-Simulacrum

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 (which might be bad with `-Z randomize-layout`)?

The replacement has [identical codegen](https://rust.godbolt.org/z/qxsvdb8nx), so it seems like a reasonable change.
  • Loading branch information
bors committed Aug 11, 2022
2 parents 908fc5b + 0cf9503 commit 1876544
Showing 1 changed file with 9 additions and 9 deletions.
18 changes: 9 additions & 9 deletions library/std/src/sys/unix/rand.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use crate::mem;
use crate::slice;

pub fn hashmap_random_keys() -> (u64, u64) {
let mut v = (0, 0);
unsafe {
let view = slice::from_raw_parts_mut(&mut v as *mut _ as *mut u8, mem::size_of_val(&v));
imp::fill_bytes(view);
}
v
const KEY_LEN: usize = core::mem::size_of::<u64>();

let mut v = [0u8; KEY_LEN * 2];
imp::fill_bytes(&mut v);

let key1 = v[0..KEY_LEN].try_into().unwrap();
let key2 = v[KEY_LEN..].try_into().unwrap();

(u64::from_ne_bytes(key1), u64::from_ne_bytes(key2))
}

#[cfg(all(
Expand Down

0 comments on commit 1876544

Please sign in to comment.