Skip to content

Commit 204643b

Browse files
authored
Merge pull request RustPython#4574 from xiaozhiyan/implement-number-protocol-for-pybytearray
Implement Number Protocol for `PyByteArray`
2 parents 547d752 + 4f206c5 commit 204643b

1 file changed

Lines changed: 21 additions & 4 deletions

File tree

vm/src/builtins/bytearray.rs

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,24 +19,26 @@ use crate::{
1919
PyRwLockReadGuard, PyRwLockWriteGuard,
2020
},
2121
},
22-
convert::ToPyObject,
22+
convert::{ToPyObject, ToPyResult},
2323
function::Either,
2424
function::{
2525
ArgBytesLike, ArgIterable, FuncArgs, OptionalArg, OptionalOption, PyComparisonValue,
2626
},
2727
protocol::{
2828
BufferDescriptor, BufferMethods, BufferResizeGuard, PyBuffer, PyIterReturn,
29-
PyMappingMethods, PySequenceMethods,
29+
PyMappingMethods, PyNumberMethods, PySequenceMethods,
3030
},
3131
sliceable::{SequenceIndex, SliceableSequenceMutOp, SliceableSequenceOp},
3232
types::{
33-
AsBuffer, AsMapping, AsSequence, Callable, Comparable, Constructor, Hashable, Initializer,
34-
IterNext, IterNextIterable, Iterable, PyComparisonOp, Unconstructible, Unhashable,
33+
AsBuffer, AsMapping, AsNumber, AsSequence, Callable, Comparable, Constructor, Hashable,
34+
Initializer, IterNext, IterNextIterable, Iterable, PyComparisonOp, Unconstructible,
35+
Unhashable,
3536
},
3637
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject,
3738
VirtualMachine,
3839
};
3940
use bstr::ByteSlice;
41+
use once_cell::sync::Lazy;
4042
use std::mem::size_of;
4143

4244
#[pyclass(module = false, name = "bytearray")]
@@ -103,6 +105,7 @@ pub(crate) fn init(context: &Context) {
103105
AsBuffer,
104106
AsMapping,
105107
AsSequence,
108+
AsNumber,
106109
Iterable
107110
)
108111
)]
@@ -856,6 +859,20 @@ impl AsSequence for PyByteArray {
856859
}
857860
}
858861

862+
impl AsNumber for PyByteArray {
863+
fn as_number() -> &'static PyNumberMethods {
864+
static AS_NUMBER: Lazy<PyNumberMethods> = Lazy::new(|| PyNumberMethods {
865+
remainder: atomic_func!(|number, other, vm| {
866+
PyByteArray::number_downcast(number)
867+
.mod_(other.to_owned(), vm)
868+
.to_pyresult(vm)
869+
}),
870+
..PyNumberMethods::NOT_IMPLEMENTED
871+
});
872+
&AS_NUMBER
873+
}
874+
}
875+
859876
impl Unhashable for PyByteArray {}
860877

861878
impl Iterable for PyByteArray {

0 commit comments

Comments
 (0)