Skip to content

Commit dd20263

Browse files
Merge pull request RustPython#1123 from corona10/fix_complex_hash
complex: Fix hash function to work correctly
2 parents b2c515c + d349d25 commit dd20263

File tree

2 files changed

+7
-2
lines changed

2 files changed

+7
-2
lines changed

tests/snippets/builtin_complex.py

+4
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,10 @@
9494
assert hash(complex(-float('inf'))) == hash(-float('inf'))
9595
assert hash(1j) != hash(1)
9696

97+
# TODO: Find a way to test platform dependent values
98+
assert hash(3.1 - 4.2j) == hash(3.1 - 4.2j)
99+
assert hash(3.1 + 4.2j) == hash(3.1 + 4.2j)
100+
97101
# numbers.Complex
98102

99103
a = complex(3, 4)

vm/src/obj/objcomplex.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use num_complex::Complex64;
22
use num_traits::Zero;
3+
use std::num::Wrapping;
34

45
use crate::function::OptionalArg;
56
use crate::pyhash;
@@ -254,7 +255,7 @@ impl PyComplex {
254255
fn hash(&self, _vm: &VirtualMachine) -> pyhash::PyHash {
255256
let re_hash = pyhash::hash_float(self.value.re);
256257
let im_hash = pyhash::hash_float(self.value.im);
257-
258-
re_hash + im_hash * pyhash::IMAG
258+
let ret = Wrapping(re_hash) + Wrapping(im_hash) * Wrapping(pyhash::IMAG);
259+
ret.0
259260
}
260261
}

0 commit comments

Comments
 (0)