Fix usize not using the same hash as PyInt when used as key into a di… (#5756)

* Fix usize not using the same hash as PyInt when used as key into a dictionary

* Fix test that unexpectedly succeed!

* Update extra_tests/snippets/builtin_object.py
This commit is contained in:
Hanif Ariffin authored and GitHub committed 2025-05-01 14:55:19 +09:00
1 parent 431b900084
commit 253cc4e846
4 files changed
+15 -4

No files matched your search

-2
View File
@@ -1631,8 +1631,6 @@ x = (
self.assertEqual(f"{x!s:}", "test")
self.assertEqual(f"{x!r:}", "'test'")
# TODO: RUSTPYTHON d[0] error
@unittest.expectedFailure
def test_str_format_differences(self):
d = {
"a": "string",
+5
View File
@@ -139,6 +139,11 @@ pub fn hash_bigint(value: &BigInt) -> PyHash {
fix_sentinel(ret)
}
#[inline]
pub fn hash_usize(data: usize) -> PyHash {
fix_sentinel(mod_int(data as i64))
}
#[inline(always)]
pub fn fix_sentinel(x: PyHash) -> PyHash {
if x == SENTINEL { -2 } else { x }
+7
View File
@@ -24,3 +24,10 @@ assert obj.__ne__(obj) is False
assert not hasattr(obj, 'a')
obj.__dict__ = {'a': 1}
assert obj.a == 1
# Value inside the formatter goes through a different path of resolution.
# Check that it still works all the same
d = {
0: "ab",
}
assert "ab ab" == "{k[0]} {vv}".format(k=d, vv=d[0])
+3 -2
View File
@@ -17,6 +17,7 @@ use crate::{
object::{Traverse, TraverseFn},
};
use num_traits::ToPrimitive;
use rustpython_common::hash::hash_integer;
use std::{fmt, mem::size_of, ops::ControlFlow};
// HashIndex is intended to be same size with hash::PyHash
@@ -993,8 +994,8 @@ impl DictKey for usize {
*self
}
fn key_hash(&self, vm: &VirtualMachine) -> PyResult<HashValue> {
Ok(vm.state.hash_secret.hash_value(self))
fn key_hash(&self, _vm: &VirtualMachine) -> PyResult<HashValue> {
Ok(hash_usize(*self))
}
fn key_is(&self, _other: &PyObject) -> bool {