Skip to content
Merged
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
Next Next commit
Fix hash wrapper overflow handling
Co-authored-by: youknowone <69878+youknowone@users.noreply.github.com>
  • Loading branch information
Copilot and youknowone committed Dec 28, 2025
commit fa233e254f4bdf46f088155dcaa9830b6bc18994
9 changes: 2 additions & 7 deletions crates/vm/src/types/slot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::{
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
builtins::{PyInt, PyStr, PyStrInterned, PyStrRef, PyType, PyTypeRef},
bytecode::ComparisonOperator,
common::hash::PyHash,
common::hash::{hash_bigint, PyHash},
convert::ToPyObject,
function::{
Either, FromArgs, FuncArgs, OptionalArg, PyComparisonValue, PyMethodDef, PySetterValue,
Expand All @@ -18,7 +18,6 @@ use crate::{
vm::Context,
};
use crossbeam_utils::atomic::AtomicCell;
use malachite_bigint::BigInt;
use num_traits::{Signed, ToPrimitive};
use std::{any::Any, any::TypeId, borrow::Borrow, cmp::Ordering, ops::Deref};

Expand Down Expand Up @@ -411,11 +410,7 @@ fn hash_wrapper(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<PyHash> {
let py_int = hash_obj
.downcast_ref::<PyInt>()
.ok_or_else(|| vm.new_type_error("__hash__ method should return an integer"))?;
let big_int = py_int.as_bigint();
let hash: PyHash = big_int
.to_i64()
.unwrap_or_else(|| (big_int % BigInt::from(u64::MAX)).to_i64().unwrap());
Ok(hash)
Ok(hash_bigint(py_int.as_bigint()))
}

/// Marks a type as unhashable. Similar to PyObject_HashNotImplemented in CPython
Expand Down
8 changes: 8 additions & 0 deletions extra_tests/snippets/builtin_hash.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ class A:
assert type(hash(1.1)) is int
assert type(hash("")) is int


class Evil:
def __hash__(self):
return 1 << 63


assert hash(Evil()) == 4

with assert_raises(TypeError):
hash({})

Expand Down
Loading