Skip to content

Commit 2224650

Browse files
committed
Impl DictKey for &PyStringRef
1 parent 5348e87 commit 2224650

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

vm/src/dictdatatype.rs

+21-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::obj::objstr::PyString;
1+
use crate::obj::objstr::{PyString, PyStringRef};
22
use crate::pyhash;
33
use crate::pyobject::{IdProtocol, IntoPyObject, PyObjectRef, PyResult};
44
use crate::vm::VirtualMachine;
@@ -438,6 +438,26 @@ impl DictKey for &PyObjectRef {
438438
}
439439
}
440440

441+
impl DictKey for &PyStringRef {
442+
fn do_hash(self, _vm: &VirtualMachine) -> PyResult<HashValue> {
443+
Ok(self.hash())
444+
}
445+
446+
fn do_is(self, other: &PyObjectRef) -> bool {
447+
self.is(other)
448+
}
449+
450+
fn do_eq(self, vm: &VirtualMachine, other_key: &PyObjectRef) -> PyResult<bool> {
451+
if self.is(other_key) {
452+
Ok(true)
453+
} else if let Some(py_str_value) = other_key.payload::<PyString>() {
454+
Ok(py_str_value.as_str() == self.as_str())
455+
} else {
456+
vm.bool_eq(self.clone().into_object(), other_key.clone())
457+
}
458+
}
459+
}
460+
441461
/// Implement trait for the str type, so that we can use strings
442462
/// to index dictionaries.
443463
impl DictKey for &str {

vm/src/obj/objstr.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,7 @@ impl PyString {
292292
}
293293

294294
#[pymethod(name = "__hash__")]
295-
fn hash(&self) -> pyhash::PyHash {
295+
pub(crate) fn hash(&self) -> pyhash::PyHash {
296296
self.hash.load().unwrap_or_else(|| {
297297
let hash = pyhash::hash_value(&self.value);
298298
self.hash.store(Some(hash));

0 commit comments

Comments
 (0)