|
| 1 | +import math |
1 | 2 | import sys |
2 | 3 | import unittest |
3 | 4 | from test.support import import_helper |
@@ -31,3 +32,49 @@ def test_hash_getfuncdef(self): |
31 | 32 | self.assertEqual(func_def.name, hash_info.algorithm) |
32 | 33 | self.assertEqual(func_def.hash_bits, hash_info.hash_bits) |
33 | 34 | self.assertEqual(func_def.seed_bits, hash_info.seed_bits) |
| 35 | + |
| 36 | + def test_hash_double(self): |
| 37 | + # Test PyHash_Double() |
| 38 | + hash_double = _testcapi.hash_double |
| 39 | + |
| 40 | + # test integers |
| 41 | + def python_hash_int(x): |
| 42 | + negative = (x < 0) |
| 43 | + x = abs(x) % sys.hash_info.modulus |
| 44 | + if negative: |
| 45 | + x = -x |
| 46 | + if x == -1: |
| 47 | + x = -2 |
| 48 | + return x |
| 49 | + |
| 50 | + integers = [ |
| 51 | + *range(1, 30), |
| 52 | + 2**30 - 1, |
| 53 | + 2 ** 233, |
| 54 | + int(sys.float_info.max), |
| 55 | + ] |
| 56 | + integers.extend([-x for x in integers]) |
| 57 | + integers.append(0) |
| 58 | + |
| 59 | + for x in integers: |
| 60 | + self.assertEqual(hash_double(float(x)), python_hash_int(x), x) |
| 61 | + |
| 62 | + # test non-finite values |
| 63 | + self.assertEqual(hash_double(float('inf')), sys.hash_info.inf) |
| 64 | + self.assertEqual(hash_double(float('-inf')), -sys.hash_info.inf) |
| 65 | + self.assertEqual(hash_double(float('nan')), -1) |
| 66 | + |
| 67 | + # special values: compare with Python hash() function |
| 68 | + def python_hash_double(x): |
| 69 | + return hash(x) |
| 70 | + |
| 71 | + special_values = ( |
| 72 | + sys.float_info.max, |
| 73 | + sys.float_info.min, |
| 74 | + sys.float_info.epsilon, |
| 75 | + math.nextafter(0.0, 1.0), |
| 76 | + ) |
| 77 | + for x in special_values: |
| 78 | + with self.subTest(x=x): |
| 79 | + self.assertEqual(hash_double(x), python_hash_double(x)) |
| 80 | + self.assertEqual(hash_double(-x), python_hash_double(-x)) |
0 commit comments