Skip to content

Commit b4124d0

Browse files
committed
Add number protocol for PyStr
1 parent f3e9413 commit b4124d0

File tree

1 file changed

+27
-5
lines changed

1 file changed

+27
-5
lines changed

vm/src/builtins/str.rs

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,16 @@ use crate::{
1111
format::{FormatSpec, FormatString, FromTemplate},
1212
str::{BorrowedStr, PyStrKind, PyStrKindData},
1313
},
14-
convert::{IntoPyException, ToPyException, ToPyObject},
14+
convert::{IntoPyException, ToPyException, ToPyObject, ToPyResult},
1515
format::{format, format_map},
1616
function::{ArgIterable, FuncArgs, OptionalArg, OptionalOption, PyComparisonValue},
1717
intern::PyInterned,
18-
protocol::{PyIterReturn, PyMappingMethods, PySequenceMethods},
18+
protocol::{PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods},
1919
sequence::SequenceExt,
2020
sliceable::{SequenceIndex, SliceableSequenceOp},
2121
types::{
22-
AsMapping, AsSequence, Comparable, Constructor, Hashable, IterNext, IterNextIterable,
23-
Iterable, PyComparisonOp, Unconstructible,
22+
AsMapping, AsNumber, AsSequence, Comparable, Constructor, Hashable, IterNext,
23+
IterNextIterable, Iterable, PyComparisonOp, Unconstructible,
2424
},
2525
AsObject, Context, Py, PyExact, PyObject, PyObjectRef, PyPayload, PyRef, PyRefExact, PyResult,
2626
TryFromBorrowedObject, VirtualMachine,
@@ -354,7 +354,15 @@ impl PyStr {
354354

355355
#[pyclass(
356356
flags(BASETYPE),
357-
with(AsMapping, AsSequence, Hashable, Comparable, Iterable, Constructor)
357+
with(
358+
AsMapping,
359+
AsNumber,
360+
AsSequence,
361+
Hashable,
362+
Comparable,
363+
Iterable,
364+
Constructor
365+
)
358366
)]
359367
impl PyStr {
360368
#[pymethod(magic)]
@@ -1281,6 +1289,20 @@ impl AsMapping for PyStr {
12811289
}
12821290
}
12831291

1292+
impl AsNumber for PyStr {
1293+
fn as_number() -> &'static PyNumberMethods {
1294+
static AS_NUMBER: Lazy<PyNumberMethods> = Lazy::new(|| PyNumberMethods {
1295+
remainder: atomic_func!(|number, other, vm| {
1296+
PyStr::number_downcast(number)
1297+
.modulo(other.to_owned(), vm)
1298+
.to_pyresult(vm)
1299+
}),
1300+
..PyNumberMethods::NOT_IMPLEMENTED
1301+
});
1302+
&AS_NUMBER
1303+
}
1304+
}
1305+
12841306
impl AsSequence for PyStr {
12851307
fn as_sequence() -> &'static PySequenceMethods {
12861308
static AS_SEQUENCE: Lazy<PySequenceMethods> = Lazy::new(|| PySequenceMethods {

0 commit comments

Comments
 (0)