Skip to content

Commit 1fece09

Browse files
authored
Merge pull request RustPython#4644 from xiaozhiyan/implement-number-protocol-for-pydict
Implement Number Protocol for `PyDict`
2 parents 9f0db9a + 6f49901 commit 1fece09

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

vm/src/builtins/dict.rs

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,11 @@ use crate::{
1616
ArgIterable, FuncArgs, KwArgs, OptionalArg, PyArithmeticValue::*, PyComparisonValue,
1717
},
1818
iter::PyExactSizeIterator,
19-
protocol::{PyIterIter, PyIterReturn, PyMappingMethods, PySequenceMethods},
19+
protocol::{PyIterIter, PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods},
2020
recursion::ReprGuard,
2121
types::{
22-
AsMapping, AsSequence, Callable, Comparable, Constructor, Hashable, Initializer, IterNext,
23-
IterNextIterable, Iterable, PyComparisonOp, Unconstructible, Unhashable,
22+
AsMapping, AsNumber, AsSequence, Callable, Comparable, Constructor, Hashable, Initializer,
23+
IterNext, IterNextIterable, Iterable, PyComparisonOp, Unconstructible, Unhashable,
2424
},
2525
vm::VirtualMachine,
2626
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyRefExact, PyResult,
@@ -209,7 +209,8 @@ impl PyDict {
209209
Hashable,
210210
Comparable,
211211
Iterable,
212-
AsSequence
212+
AsSequence,
213+
AsNumber
213214
),
214215
flags(BASETYPE)
215216
)]
@@ -477,6 +478,26 @@ impl AsSequence for PyDict {
477478
}
478479
}
479480

481+
impl AsNumber for PyDict {
482+
fn as_number() -> &'static PyNumberMethods {
483+
static AS_NUMBER: Lazy<PyNumberMethods> = Lazy::new(|| PyNumberMethods {
484+
or: atomic_func!(|num, args, vm| {
485+
PyDict::number_downcast(num).or(args.to_pyobject(vm), vm)
486+
}),
487+
inplace_or: atomic_func!(|num, args, vm| {
488+
PyDict::ior(
489+
PyDict::number_downcast(num).to_owned(),
490+
args.to_pyobject(vm),
491+
vm,
492+
)
493+
.map(|d| d.into())
494+
}),
495+
..PyNumberMethods::NOT_IMPLEMENTED
496+
});
497+
&AS_NUMBER
498+
}
499+
}
500+
480501
impl Comparable for PyDict {
481502
fn cmp(
482503
zelf: &Py<Self>,

0 commit comments

Comments
 (0)