Skip to content

Commit 98d3f38

Browse files
committed
Reflect feedbacks
1 parent 0605690 commit 98d3f38

File tree

2 files changed

+27
-11
lines changed

2 files changed

+27
-11
lines changed

common/src/hash.rs

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -94,17 +94,18 @@ impl HashSecret {
9494
}
9595
}
9696

97-
pub fn hash_float(value: f64) -> PyHash {
97+
#[inline]
98+
pub fn hash_float(value: f64) -> Option<PyHash> {
9899
// cpython _Py_HashDouble
99100
if !value.is_finite() {
100101
return if value.is_infinite() {
101102
if value > 0.0 {
102-
INF
103+
Some(INF)
103104
} else {
104-
-INF
105+
Some(-INF)
105106
}
106107
} else {
107-
NAN
108+
None
108109
};
109110
}
110111

@@ -136,12 +137,12 @@ pub fn hash_float(value: f64) -> PyHash {
136137
};
137138
x = ((x << e) & MODULUS) | x >> (BITS32 - e);
138139

139-
fix_sentinel(x as PyHash * value.signum() as PyHash)
140+
Some(fix_sentinel(x as PyHash * value.signum() as PyHash))
140141
}
141142

142143
pub fn hash_complex(value: &Complex64) -> PyHash {
143-
let re_hash = hash_float(value.re);
144-
let im_hash = hash_float(value.im);
144+
let re_hash = hash_float(value.re).unwrap();
145+
let im_hash = hash_float(value.im).unwrap();
145146
let Wrapping(ret) = Wrapping(re_hash) + Wrapping(im_hash) * Wrapping(IMAG);
146147
fix_sentinel(ret)
147148
}
@@ -192,3 +193,19 @@ pub fn lcg_urandom(mut x: u32, buf: &mut [u8]) {
192193
*b = ((x >> 16) & 0xff) as u8;
193194
}
194195
}
196+
197+
pub fn hash_pointer_raw(p: *const libc::c_void) -> PyHash {
198+
// TODO: Use commented logic when below issue resolved.
199+
// Ref: https://github.com/RustPython/RustPython/pull/3951#issuecomment-1193108966
200+
201+
// let mut y = p as usize;
202+
// /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid
203+
// excessive hash collisions for dicts and sets */
204+
// y = (y >> 4) | (y << (8 * std::mem::size_of::<usize>() - 4));
205+
// y as PyHash
206+
p as PyHash
207+
}
208+
209+
pub fn hash_pointer(p: *const libc::c_void) -> PyHash {
210+
fix_sentinel(hash_pointer_raw(p))
211+
}

vm/src/builtins/float.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -539,10 +539,9 @@ impl Comparable for PyFloat {
539539
impl Hashable for PyFloat {
540540
#[inline]
541541
fn hash(zelf: &crate::Py<Self>, _vm: &VirtualMachine) -> PyResult<hash::PyHash> {
542-
if zelf.to_f64().is_nan() {
543-
Ok(zelf.get_id() as hash::PyHash)
544-
} else {
545-
Ok(hash::hash_float(zelf.to_f64()))
542+
match hash::hash_float(zelf.to_f64()) {
543+
Some(value) => Ok(value),
544+
None => Ok(hash::hash_pointer(zelf as *const _ as *const libc::c_void)),
546545
}
547546
}
548547
}

0 commit comments

Comments
 (0)