Skip to content

complex: Fix hash function to work correctly #1123

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 10, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions tests/snippets/builtin_complex.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@
assert hash(complex(-float('inf'))) == hash(-float('inf'))
assert hash(1j) != hash(1)

# TODO: Find a way to test platform dependent values
assert hash(3.1 - 4.2j) == hash(3.1 - 4.2j)
assert hash(3.1 + 4.2j) == hash(3.1 + 4.2j)

# numbers.Complex

a = complex(3, 4)
Expand Down
5 changes: 3 additions & 2 deletions vm/src/obj/objcomplex.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use num_complex::Complex64;
use num_traits::Zero;
use std::num::Wrapping;

use crate::function::OptionalArg;
use crate::pyhash;
Expand Down Expand Up @@ -254,7 +255,7 @@ impl PyComplex {
fn hash(&self, _vm: &VirtualMachine) -> pyhash::PyHash {
let re_hash = pyhash::hash_float(self.value.re);
let im_hash = pyhash::hash_float(self.value.im);

re_hash + im_hash * pyhash::IMAG
let ret = Wrapping(re_hash) + Wrapping(im_hash) * Wrapping(pyhash::IMAG);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting stuff, this wrapping! Thanks!

ret.0
}
}