Skip to content

Commit 22be6c8

Browse files
committed
Implement array __iadd__
1 parent 0d01493 commit 22be6c8

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

Lib/test/test_array.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -562,8 +562,6 @@ def test_add(self):
562562

563563
self.assertRaises(TypeError, a.__add__, "bad")
564564

565-
# TODO: RUSTPYTHON
566-
@unittest.expectedFailure
567565
def test_iadd(self):
568566
a = array.array(self.typecode, self.example[::-1])
569567
b = a

vm/src/stdlib/array.rs

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,17 @@ macro_rules! def_array_enum {
354354
}
355355
}
356356

357+
fn iadd(&mut self, other: ArrayContentType, vm: &VirtualMachine) -> PyResult<()> {
358+
match self {
359+
$(ArrayContentType::$n(v) => if let ArrayContentType::$n(mut other) = other {
360+
v.append(&mut other);
361+
Ok(())
362+
} else {
363+
Err(vm.new_type_error("can only extend with array of same kind".to_owned()))
364+
},)*
365+
}
366+
}
367+
357368
fn repr(&self, _vm: &VirtualMachine) -> PyResult<String> {
358369
// we don't need ReprGuard here
359370
let s = match self {
@@ -604,7 +615,24 @@ impl PyArray {
604615
if let Some(other) = other.payload::<PyArray>() {
605616
self.borrow_value().add(&*other.borrow_value(), vm)
606617
} else {
607-
Err(vm.new_type_error(format!("can only append array (not \"{}\") to array", other.class().name)))
618+
Err(vm.new_type_error(format!(
619+
"can only append array (not \"{}\") to array",
620+
other.class().name
621+
)))
622+
}
623+
}
624+
625+
#[pymethod(name = "__iadd__")]
626+
fn iadd(zelf: PyRef<Self>, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
627+
if let Some(other) = other.payload::<PyArray>() {
628+
let other = other.borrow_value().clone();
629+
let result = zelf.borrow_value_mut().iadd(other, vm);
630+
result.map(|_| zelf.into_object())
631+
} else {
632+
Err(vm.new_type_error(format!(
633+
"can only extend array with array (not \"{}\")",
634+
other.class().name
635+
)))
608636
}
609637
}
610638

0 commit comments

Comments
 (0)