Skip to content
Draft
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
1 change: 0 additions & 1 deletion Lib/test/test_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,6 @@ def test_cyclical_repr(self):
name = repr(s).partition('(')[0] # strip class name
self.assertEqual(repr(s), '%s({%s(...)})' % (name, name))

@unittest.expectedFailure # TODO: RUSTPYTHON
def test_do_not_rehash_dict_keys(self):
n = 10
d = dict.fromkeys(map(HashCountingInt, range(n)))
Expand Down
30 changes: 26 additions & 4 deletions crates/vm/src/builtins/dict.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::{
IterStatus, PositionIterInternal, PyBaseExceptionRef, PyGenericAlias, PyMappingProxy, PySet,
PyStr, PyStrRef, PyTupleRef, PyType, PyTypeRef, set::PySetInner,
PyStr, PyStrRef, PyTupleRef, PyType, PyTypeRef, set, set::PySetInner,
};
use crate::common::lock::LazyLock;
use crate::object::{Traverse, TraverseFn};
Expand All @@ -9,7 +9,7 @@ use crate::{
TryFromObject, atomic_func,
builtins::{PyList, PyTuple, iter::builtins_iter, type_::PyAttributes},
class::{PyClassDef, PyClassImpl},
common::ascii,
common::{ascii, hash::PyHash},
dict_inner::{self, DictKey},
function::{ArgIterable, FuncArgs, KwArgs, OptionalArg, PyArithmeticValue, PyComparisonValue},
iter::PyExactSizeIterator,
Expand Down Expand Up @@ -356,6 +356,20 @@ impl PyDict {
}
}

/// Keys of `obj` with their stored hashes, or `None` if it must be iterated
/// generically. Only exact dicts and sets qualify, as in CPython's
/// `_PyDict_FromKeys`: a subclass may override `__iter__`.
fn fromkeys_known_hashes(
obj: &PyObject,
vm: &VirtualMachine,
) -> Option<Vec<(PyObjectRef, PyHash)>> {
if let Some(dict) = obj.downcast_ref_if_exact::<PyDict>(vm) {
Some(dict.entries.keys_with_hashes())
} else {
set::exact_set_keys_with_hashes(obj, vm)
}
}

// Python dict methods:
#[pyclass(
with(
Expand Down Expand Up @@ -384,8 +398,16 @@ impl PyDict {
let d = PyType::call(&class, ().into(), vm)?;
match d.downcast_exact::<Self>(vm) {
Ok(pydict) => {
for key in iterable.iter(vm)? {
pydict.__setitem__(key?, value.clone(), vm)?;
if let Some(keys) = fromkeys_known_hashes(iterable.as_object(), vm) {
for (key, hash) in keys {
pydict
.entries
.insert_known_hash(vm, &*key, hash, value.clone())?;
}
} else {
for key in iterable.iter(vm)? {
pydict.__setitem__(key?, value.clone(), vm)?;
}
}
Ok(pydict.into_pyref().into())
}
Expand Down
17 changes: 17 additions & 0 deletions crates/vm/src/builtins/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,23 @@ fn extract_set(obj: &PyObject) -> Option<&PySetInner> {
})
}

/// Elements of `obj` with their stored hashes, or `None` unless `obj` is exactly
/// a `set` or `frozenset` — `PyAnySet_CheckExact`, where [`extract_set`] is the
/// subclass-inclusive `PyAnySet_Check`.
pub(super) fn exact_set_keys_with_hashes(
obj: &PyObject,
vm: &VirtualMachine,
) -> Option<Vec<(PyObjectRef, PyHash)>> {
let inner = obj
.downcast_ref_if_exact::<PySet>(vm)
.map(|set| &set.inner)
.or_else(|| {
obj.downcast_ref_if_exact::<PyFrozenSet>(vm)
.map(|frozen| &frozen.inner)
})?;
Some(inner.content.keys_with_hashes())
}

fn reduce_set(zelf: &PyObject, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef, Option<PyDictRef>) {
(
zelf.class().to_owned(),
Expand Down
Loading