|
| 1 | +import math |
| 2 | +import sys |
| 3 | +import unittest |
| 4 | +from test.support import import_helper |
| 5 | +_testcapi = import_helper.import_module('_testcapi') |
| 6 | + |
| 7 | + |
| 8 | +PyHASH_INF = sys.hash_info.inf |
| 9 | +if _testcapi.SIZEOF_VOID_P >= 8: |
| 10 | + PyHASH_BITS = 61 |
| 11 | +else: |
| 12 | + PyHASH_BITS = 31 |
| 13 | +PyHASH_MODULUS = ((1 << PyHASH_BITS) - 1) |
| 14 | + |
| 15 | + |
| 16 | +class CAPITest(unittest.TestCase): |
| 17 | + def test_hash_double(self): |
| 18 | + # Test PyHash_Double() |
| 19 | + hash_double = _testcapi.hash_double |
| 20 | + |
| 21 | + # test integers |
| 22 | + def python_hash_int(x): |
| 23 | + negative = (x < 0) |
| 24 | + x = abs(x) % PyHASH_MODULUS |
| 25 | + if negative: |
| 26 | + x = -x |
| 27 | + if x == -1: |
| 28 | + x = -2 |
| 29 | + return x |
| 30 | + |
| 31 | + integers = [ |
| 32 | + *range(1, 30), |
| 33 | + 2**30 - 1, |
| 34 | + 2 ** 233, |
| 35 | + int(sys.float_info.max), |
| 36 | + ] |
| 37 | + integers.extend([-x for x in integers]) |
| 38 | + integers.append(0) |
| 39 | + |
| 40 | + for x in integers: |
| 41 | + self.assertEqual(hash_double(float(x)), python_hash_int(x), x) |
| 42 | + |
| 43 | + # test non-finite values |
| 44 | + self.assertEqual(hash_double(float('inf')), PyHASH_INF) |
| 45 | + self.assertEqual(hash_double(float('-inf')), -PyHASH_INF) |
| 46 | + self.assertEqual(hash_double(float('nan')), -1) |
| 47 | + |
| 48 | + # special values: compare with Python hash() function |
| 49 | + def python_hash_double(x): |
| 50 | + return hash(x) |
| 51 | + |
| 52 | + special_values = ( |
| 53 | + sys.float_info.max, |
| 54 | + sys.float_info.min, |
| 55 | + sys.float_info.epsilon, |
| 56 | + math.nextafter(0.0, 1.0), |
| 57 | + ) |
| 58 | + for x in special_values: |
| 59 | + with self.subTest(x=x): |
| 60 | + self.assertEqual(hash_double(x), python_hash_double(x)) |
| 61 | + self.assertEqual(hash_double(-x), python_hash_double(-x)) |
0 commit comments