|
| 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 = 314159 |
| 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 | + integers = [*range(0, 10), 2**30 - 1, 2 ** 233] |
| 23 | + integers.extend([-x for x in integers]) |
| 24 | + for x in integers: |
| 25 | + expected = abs(x) % PyHASH_MODULUS |
| 26 | + if x < 0: |
| 27 | + expected = -expected |
| 28 | + if expected == -1: |
| 29 | + expected = -2 |
| 30 | + self.assertEqual(hash_double(float(x)), expected, x) |
| 31 | + |
| 32 | + # test non-finite values |
| 33 | + self.assertEqual(hash_double(float('inf')), PyHASH_INF) |
| 34 | + self.assertEqual(hash_double(float('-inf')), -PyHASH_INF) |
| 35 | + self.assertEqual(hash_double(float('nan')), -1) |
| 36 | + |
| 37 | + # special values: compare with Python hash() function |
| 38 | + def python_hash_double(x): |
| 39 | + return hash(x) |
| 40 | + |
| 41 | + special_values = ( |
| 42 | + sys.float_info.max, |
| 43 | + sys.float_info.min, |
| 44 | + sys.float_info.epsilon, |
| 45 | + math.nextafter(0.0, 1.0), |
| 46 | + ) |
| 47 | + for x in special_values: |
| 48 | + with self.subTest(x=x): |
| 49 | + self.assertEqual(hash_double(x), python_hash_double(x)) |
| 50 | + self.assertEqual(hash_double(-x), python_hash_double(-x)) |
0 commit comments