Skip to content

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

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

Merged
merged 7 commits into from
May 1, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 0 additions & 2 deletions Lib/test/test_fstring.py
Original file line number Diff line number Diff line change
Expand Up @@ -1631,8 +1631,6 @@ def test_empty_format_specifier(self):
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",
Expand Down
5 changes: 5 additions & 0 deletions common/src/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
7 changes: 7 additions & 0 deletions extra_tests/snippets/builtin_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,10 @@ class MyObject:
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])
5 changes: 3 additions & 2 deletions vm/src/dict_inner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down