Skip to content

Commit cdf5634

Browse files
authored
Implement as_sequence for array (#4585)
1 parent 2d02933 commit cdf5634

File tree

1 file changed

+44
-3
lines changed

1 file changed

+44
-3
lines changed

stdlib/src/array.rs

+44-3
Original file line numberDiff line numberDiff line change
@@ -50,16 +50,16 @@ mod array {
5050
function::{ArgBytesLike, ArgIntoFloat, ArgIterable, OptionalArg, PyComparisonValue},
5151
protocol::{
5252
BufferDescriptor, BufferMethods, BufferResizeGuard, PyBuffer, PyIterReturn,
53-
PyMappingMethods,
53+
PyMappingMethods, PySequenceMethods,
5454
},
5555
sequence::{OptionalRangeArgs, SequenceExt, SequenceMutExt},
5656
sliceable::{
5757
SaturatedSlice, SequenceIndex, SequenceIndexOp, SliceableSequenceMutOp,
5858
SliceableSequenceOp,
5959
},
6060
types::{
61-
AsBuffer, AsMapping, Comparable, Constructor, IterNext, IterNextIterable, Iterable,
62-
PyComparisonOp,
61+
AsBuffer, AsMapping, AsSequence, Comparable, Constructor, IterNext,
62+
IterNextIterable, Iterable, PyComparisonOp,
6363
},
6464
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
6565
},
@@ -1315,6 +1315,47 @@ mod array {
13151315
}
13161316
}
13171317

1318+
impl AsSequence for PyArray {
1319+
fn as_sequence() -> &'static PySequenceMethods {
1320+
static AS_SEQUENCE: PySequenceMethods = PySequenceMethods {
1321+
length: atomic_func!(|seq, _vm| Ok(PyArray::sequence_downcast(seq).len())),
1322+
concat: atomic_func!(|seq, other, vm| {
1323+
let zelf = PyArray::sequence_downcast(seq);
1324+
PyArray::add(zelf, other.to_owned(), vm).map(|x| x.into())
1325+
}),
1326+
repeat: atomic_func!(|seq, n, vm| {
1327+
PyArray::sequence_downcast(seq).mul(n, vm).map(|x| x.into())
1328+
}),
1329+
item: atomic_func!(|seq, i, vm| {
1330+
PyArray::sequence_downcast(seq)
1331+
.read()
1332+
.getitem_by_index(i, vm)
1333+
}),
1334+
ass_item: atomic_func!(|seq, i, value, vm| {
1335+
let zelf = PyArray::sequence_downcast(seq);
1336+
if let Some(value) = value {
1337+
zelf.write().setitem_by_index(i, value, vm)
1338+
} else {
1339+
zelf.write().delitem_by_index(i, vm)
1340+
}
1341+
}),
1342+
contains: atomic_func!(|seq, target, vm| {
1343+
let zelf = PyArray::sequence_downcast(seq);
1344+
Ok(zelf.contains(target.to_owned(), vm))
1345+
}),
1346+
inplace_concat: atomic_func!(|seq, other, vm| {
1347+
let zelf = PyArray::sequence_downcast(seq).to_owned();
1348+
PyArray::iadd(zelf, other.to_owned(), vm).map(|x| x.into())
1349+
}),
1350+
inplace_repeat: atomic_func!(|seq, n, vm| {
1351+
let zelf = PyArray::sequence_downcast(seq).to_owned();
1352+
PyArray::imul(zelf, n, vm).map(|x| x.into())
1353+
}),
1354+
};
1355+
&AS_SEQUENCE
1356+
}
1357+
}
1358+
13181359
impl Iterable for PyArray {
13191360
fn iter(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult {
13201361
Ok(PyArrayIter {

0 commit comments

Comments
 (0)