Skip to content
Closed
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
Next Next commit
Fix usize not using the same hash as PyInt when used as key into a di…
…ctionary
  • Loading branch information
hbina committed Apr 30, 2025
commit 627bdadf010d9c8be8bad00bc4cbc5ec17dbc2b5
5 changes: 5 additions & 0 deletions common/src/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,11 @@ pub fn hash_pointer(value: usize) -> PyHash {
hash as _
}

#[inline]
pub fn hash_integer<T: num_traits::PrimInt>(data: T) -> PyHash {
fix_sentinel(mod_int(data.to_i64().unwrap()))
}

#[inline]
pub fn hash_float(value: f64) -> Option<PyHash> {
// cpython _Py_HashDouble
Expand Down
8 changes: 8 additions & 0 deletions extra_tests/snippets/builtin_object.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
class MyObject:
pass


assert not MyObject() == MyObject()
assert MyObject() != MyObject()
myobj = MyObject()
Expand All @@ -24,3 +25,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_integer(*self))
}

fn key_is(&self, _other: &PyObject) -> bool {
Expand Down