Skip to content

Commit

Permalink
Fix test on 32-bit
Browse files Browse the repository at this point in the history
  • Loading branch information
vstinner committed Nov 15, 2023
1 parent 8bb71fe commit d132eb6
Showing 1 changed file with 25 additions and 13 deletions.
38 changes: 25 additions & 13 deletions Lib/test/test_capi/test_hash.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
_testcapi = import_helper.import_module('_testcapi')


SIZEOF_PY_HASH_T = _testcapi.SIZEOF_VOID_P
SIZEOF_VOID_P = _testcapi.SIZEOF_VOID_P
SIZEOF_PY_HASH_T = SIZEOF_VOID_P


class CAPITest(unittest.TestCase):
Expand Down Expand Up @@ -36,10 +37,8 @@ def test_hash_pointer(self):
# Test PyHash_Pointer()
hash_pointer = _testcapi.hash_pointer

HASH_BITS = 8 * _testcapi.SIZEOF_VOID_P
UHASH_T_MASK = ((2 ** HASH_BITS) - 1)
HASH_T_MAX = (2 ** (HASH_BITS - 1) - 1)
MAX_PTR = UHASH_T_MASK
UHASH_T_MASK = ((2 ** (8 * SIZEOF_PY_HASH_T)) - 1)
HASH_T_MAX = (2 ** (8 * SIZEOF_PY_HASH_T - 1) - 1)

def uhash_to_hash(x):
# Convert unsigned Py_uhash_t to signed Py_hash_t
Expand All @@ -49,12 +48,25 @@ def uhash_to_hash(x):
x = (~x) + 1
return x

# Known values
# PyHash_Pointer() rotates the pointer bits by 4 bits to the right
if SIZEOF_VOID_P == 8:
self.assertEqual(hash_pointer(0xABCDEF1234567890),
0x0ABCDEF123456789)
self.assertEqual(hash_pointer(0x1234567890ABCDEF),
uhash_to_hash(0xF1234567890ABCDE))
self.assertEqual(hash_pointer(0xFEE4ABEDD1CECA5E),
uhash_to_hash(0xEFEE4ABEDD1CECA5))
else:
self.assertEqual(hash_pointer(0x12345678),
uhash_to_hash(0x81234567))
self.assertEqual(hash_pointer(0x1234ABCD),
uhash_to_hash(0xD1234ABC))
self.assertEqual(hash_pointer(0xDEADCAFE),
uhash_to_hash(0xEDEADCAF))

# PyHash_Pointer(NULL) returns 0
self.assertEqual(hash_pointer(0), 0)
self.assertEqual(hash_pointer(MAX_PTR), -2)
self.assertEqual(hash_pointer(0xABCDEF1234567890),
0x0ABCDEF123456789)
self.assertEqual(hash_pointer(0x1234567890ABCDEF),
uhash_to_hash(0xF1234567890ABCDE))
self.assertEqual(hash_pointer(0xFEE4ABEDD1CECA5E),
uhash_to_hash(0xEFEE4ABEDD1CECA5))

# PyHash_Pointer((void*)(uintptr_t)-1) doesn't return -1 but -2
VOID_P_MAX = -1 & (2 ** (8 * SIZEOF_VOID_P) - 1)
self.assertEqual(hash_pointer(VOID_P_MAX), -2)

0 comments on commit d132eb6

Please sign in to comment.