Skip to content

Commit d332c1f

Browse files
committed
Implement array __mul__ and __rmul__
1 parent 22be6c8 commit d332c1f

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

Lib/test/test_array.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,6 @@ def test_bad_constructor(self):
3838
self.assertRaises(TypeError, array.array, 'xx')
3939
self.assertRaises(ValueError, array.array, 'x')
4040

41-
# TODO: RUSTPYTHON
42-
@unittest.expectedFailure
4341
def test_empty(self):
4442
# Exercise code for handling zero-length arrays
4543
a = array.array('B')
@@ -583,8 +581,6 @@ def test_iadd(self):
583581

584582
self.assertRaises(TypeError, a.__iadd__, "bad")
585583

586-
# TODO: RUSTPYTHON
587-
@unittest.expectedFailure
588584
def test_mul(self):
589585
a = 5*array.array(self.typecode, self.example)
590586
self.assertEqual(

vm/src/stdlib/array.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,23 @@ macro_rules! def_array_enum {
365365
}
366366
}
367367

368+
fn mul(&self, counter: isize, vm: &VirtualMachine) -> PyObjectRef {
369+
let counter = if counter < 0 { 0 } else { counter as usize };
370+
match self {
371+
$(ArrayContentType::$n(v) => {
372+
let elements = v.iter().cycle().take(v.len() * counter).cloned().collect();
373+
let sliced = ArrayContentType::$n(elements);
374+
PyObject::new(
375+
PyArray {
376+
array: PyRwLock::new(sliced)
377+
},
378+
PyArray::class(vm),
379+
None
380+
)
381+
})*
382+
}
383+
}
384+
368385
fn repr(&self, _vm: &VirtualMachine) -> PyResult<String> {
369386
// we don't need ReprGuard here
370387
let s = match self {
@@ -636,6 +653,16 @@ impl PyArray {
636653
}
637654
}
638655

656+
#[pymethod(name = "__mul__")]
657+
fn mul(&self, counter: isize, vm: &VirtualMachine) -> PyObjectRef {
658+
self.borrow_value().mul(counter, vm)
659+
}
660+
661+
#[pymethod(name = "__rmul__")]
662+
fn rmul(&self, counter: isize, vm: &VirtualMachine) -> PyObjectRef {
663+
self.mul(counter, &vm)
664+
}
665+
639666
#[pymethod(name = "__repr__")]
640667
fn repr(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<String> {
641668
zelf.borrow_value().repr(vm)

0 commit comments

Comments
 (0)