Skip to content

gh-136599: Improve long_hash #136600

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
review comments
  • Loading branch information
eendebakpt committed Jul 25, 2025
commit 08d7ba93e78d88ec3b8edab77ef2553c26b4417e
14 changes: 11 additions & 3 deletions Lib/test/test_long.py
Original file line number Diff line number Diff line change
Expand Up @@ -1696,10 +1696,18 @@ class MyInt(int):
def test_hash(self):
# gh-136599
self.assertEqual(hash(-1), -2)
self.assertEqual(hash(0), 0)
self.assertEqual(hash(10), 10)
self.assertEqual(hash(2**31 - 2), 2**31 - 2)
self.assertNotEqual(hash(-2**31), -1)
self.assertNotEqual(hash(-2**61), -1)

self.assertEqual(hash(sys.hash_info.modulus - 2), sys.hash_info.modulus - 2)
self.assertEqual(hash(sys.hash_info.modulus - 1), sys.hash_info.modulus - 1)
self.assertEqual(hash(sys.hash_info.modulus), 0)
self.assertEqual(hash(sys.hash_info.modulus + 1), 1)

self.assertEqual(hash(-sys.hash_info.modulus - 2), -2)
self.assertEqual(hash(-sys.hash_info.modulus - 1), -2)
self.assertEqual(hash(-sys.hash_info.modulus), 0)
self.assertEqual(hash(-sys.hash_info.modulus + 1), - (sys.hash_info.modulus - 1))


if __name__ == "__main__":
Expand Down
4 changes: 3 additions & 1 deletion Objects/longobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -3678,11 +3678,13 @@ long_hash(PyObject *obj)
sign = _PyLong_NonCompactSign(v);

// unroll first two digits
#if ( PyHASH_BITS > PyLong_SHIFT )
assert(i>=2);
--i;
x = v->long_value.ob_digit[i];
assert(x < _PyHASH_MODULUS);
#if ( PyHASH_BITS > (2*PyLong_SHIFT))
#endif
#if ( PyHASH_BITS > (2 * PyLong_SHIFT) )
--i;
x = ((x << PyLong_SHIFT));
x += v->long_value.ob_digit[i];
Expand Down
Loading