From d349d254f63f3f5c795d3e2e65174d037f096829 Mon Sep 17 00:00:00 2001 From: Dong-hee Na Date: Wed, 10 Jul 2019 01:53:00 +0900 Subject: [PATCH] complex: Fix hash function to work correctly Currently, hash(3.1-4.2j) or hash(3.1+4.2j) is crashed due to overflow error on RustPython. This patch will fix this issue. --- tests/snippets/builtin_complex.py | 4 ++++ vm/src/obj/objcomplex.rs | 5 +++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/tests/snippets/builtin_complex.py b/tests/snippets/builtin_complex.py index 87e25b9b38..64b4570c1f 100644 --- a/tests/snippets/builtin_complex.py +++ b/tests/snippets/builtin_complex.py @@ -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) diff --git a/vm/src/obj/objcomplex.rs b/vm/src/obj/objcomplex.rs index 436634e9c4..b32fd8f74d 100644 --- a/vm/src/obj/objcomplex.rs +++ b/vm/src/obj/objcomplex.rs @@ -1,5 +1,6 @@ use num_complex::Complex64; use num_traits::Zero; +use std::num::Wrapping; use crate::function::OptionalArg; use crate::pyhash; @@ -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); + ret.0 } }