Debian Codegraph @

Lib/test/test_capi/test_hash.py

raw
1 import sys
2 import unittest
3 from test.support import import_helper
4 _testcapi = import_helper.import_module('_testcapi')
5
6
7 SIZEOF_VOID_P = _testcapi.SIZEOF_VOID_P
8 SIZEOF_PY_HASH_T = SIZEOF_VOID_P
9
10
11 class CAPITest(unittest.TestCase):
12 def test_hash_getfuncdef(self):
13 # Test PyHash_GetFuncDef()
14 hash_getfuncdef = _testcapi.hash_getfuncdef
15 func_def = hash_getfuncdef()
16
17 match func_def.name:
18 case "fnv":
19 self.assertEqual(func_def.hash_bits, 8 * SIZEOF_PY_HASH_T)
20 self.assertEqual(func_def.seed_bits, 16 * SIZEOF_PY_HASH_T)
21 case "siphash13":
22 self.assertEqual(func_def.hash_bits, 64)
23 self.assertEqual(func_def.seed_bits, 128)
24 case "siphash24":
25 self.assertEqual(func_def.hash_bits, 64)
26 self.assertEqual(func_def.seed_bits, 128)
27 case _:
28 self.fail(f"unknown function name: {func_def.name!r}")
29
30 # compare with sys.hash_info
31 hash_info = sys.hash_info
32 self.assertEqual(func_def.name, hash_info.algorithm)
33 self.assertEqual(func_def.hash_bits, hash_info.hash_bits)
34 self.assertEqual(func_def.seed_bits, hash_info.seed_bits)
35
36 def test_hash_pointer(self):
37 # Test Py_HashPointer()
38 hash_pointer = _testcapi.hash_pointer
39
40 UHASH_T_MASK = ((2 ** (8 * SIZEOF_PY_HASH_T)) - 1)
41 HASH_T_MAX = (2 ** (8 * SIZEOF_PY_HASH_T - 1) - 1)
42
43 def python_hash_pointer(x):
44 # Py_HashPointer() rotates the pointer bits by 4 bits to the right
45 x = (x >> 4) | ((x & 15) << (8 * SIZEOF_VOID_P - 4))
46
47 # Convert unsigned uintptr_t (Py_uhash_t) to signed Py_hash_t
48 if HASH_T_MAX < x:
49 x = (~x) + 1
50 x &= UHASH_T_MASK
51 x = (~x) + 1
52 return x
53
54 if SIZEOF_VOID_P == 8:
55 values = (
56 0xABCDEF1234567890,
57 0x1234567890ABCDEF,
58 0xFEE4ABEDD1CECA5E,
59 )
60 else:
61 values = (
62 0x12345678,
63 0x1234ABCD,
64 0xDEADCAFE,
65 )
66
67 for value in values:
68 expected = python_hash_pointer(value)
69 with self.subTest(value=value):
70 self.assertEqual(hash_pointer(value), expected,
71 f"hash_pointer({value:x}) = "
72 f"{hash_pointer(value):x} != {expected:x}")
73
74 # Py_HashPointer(NULL) returns 0
75 self.assertEqual(hash_pointer(0), 0)
76
77 # Py_HashPointer((void*)(uintptr_t)-1) doesn't return -1 but -2
78 VOID_P_MAX = -1 & (2 ** (8 * SIZEOF_VOID_P) - 1)
79 self.assertEqual(hash_pointer(VOID_P_MAX), -2)
80
81 def test_hash_buffer(self):
82 hash_buffer = _testcapi.hash_buffer
83
84 def check(data):
85 self.assertEqual(hash_buffer(data), hash(data))
86
87 check(b'')
88 check(b'abc')
89 check(b'x' * 1024)
90
91
92 if __name__ == "__main__":
93 unittest.main()