From 98d3f38476a784378e3e1730cf4b1efded4bd572 Mon Sep 17 00:00:00 2001 From: Gyubong Lee Date: Sun, 24 Jul 2022 11:36:07 +0900 Subject: [PATCH] Reflect feedbacks --- common/src/hash.rs | 31 ++++++++++++++++++++++++------- vm/src/builtins/float.rs | 7 +++---- 2 files changed, 27 insertions(+), 11 deletions(-) diff --git a/common/src/hash.rs b/common/src/hash.rs index ba3d6048a..6f699e03d 100644 --- a/common/src/hash.rs +++ b/common/src/hash.rs @@ -94,17 +94,18 @@ impl HashSecret { } } -pub fn hash_float(value: f64) -> PyHash { +#[inline] +pub fn hash_float(value: f64) -> Option { // cpython _Py_HashDouble if !value.is_finite() { return if value.is_infinite() { if value > 0.0 { - INF + Some(INF) } else { - -INF + Some(-INF) } } else { - NAN + None }; } @@ -136,12 +137,12 @@ pub fn hash_float(value: f64) -> PyHash { }; x = ((x << e) & MODULUS) | x >> (BITS32 - e); - fix_sentinel(x as PyHash * value.signum() as PyHash) + Some(fix_sentinel(x as PyHash * value.signum() as PyHash)) } pub fn hash_complex(value: &Complex64) -> PyHash { - let re_hash = hash_float(value.re); - let im_hash = hash_float(value.im); + let re_hash = hash_float(value.re).unwrap(); + let im_hash = hash_float(value.im).unwrap(); let Wrapping(ret) = Wrapping(re_hash) + Wrapping(im_hash) * Wrapping(IMAG); fix_sentinel(ret) } @@ -192,3 +193,19 @@ pub fn lcg_urandom(mut x: u32, buf: &mut [u8]) { *b = ((x >> 16) & 0xff) as u8; } } + +pub fn hash_pointer_raw(p: *const libc::c_void) -> PyHash { + // TODO: Use commented logic when below issue resolved. + // Ref: https://github.com/RustPython/RustPython/pull/3951#issuecomment-1193108966 + + // let mut y = p as usize; + // /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid + // excessive hash collisions for dicts and sets */ + // y = (y >> 4) | (y << (8 * std::mem::size_of::() - 4)); + // y as PyHash + p as PyHash +} + +pub fn hash_pointer(p: *const libc::c_void) -> PyHash { + fix_sentinel(hash_pointer_raw(p)) +} diff --git a/vm/src/builtins/float.rs b/vm/src/builtins/float.rs index 0e047d499..dfa932a42 100644 --- a/vm/src/builtins/float.rs +++ b/vm/src/builtins/float.rs @@ -539,10 +539,9 @@ impl Comparable for PyFloat { impl Hashable for PyFloat { #[inline] fn hash(zelf: &crate::Py, _vm: &VirtualMachine) -> PyResult { - if zelf.to_f64().is_nan() { - Ok(zelf.get_id() as hash::PyHash) - } else { - Ok(hash::hash_float(zelf.to_f64())) + match hash::hash_float(zelf.to_f64()) { + Some(value) => Ok(value), + None => Ok(hash::hash_pointer(zelf as *const _ as *const libc::c_void)), } } }