Skip to content

Commit bbe333d

Browse files
Merge pull request RustPython#233 from rossjones/232-impl-mul-for-list
Implements __mul__ for lists
2 parents 8aaadb1 + ae2f7ed commit bbe333d

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

tests/snippets/list.py

+2
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,5 @@
99
y.extend(x)
1010
assert y == [2, 1, 2, 3, 1, 2, 3]
1111

12+
assert x * 0 == [], "list __mul__ by 0 failed"
13+
assert x * 2 == [1, 2, 3, 1, 2, 3], "list __mul__ by 2 failed"

vm/src/obj/objlist.rs

+29
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,34 @@ fn list_setitem(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
232232
set_item(vm, &mut elements, key.clone(), value.clone())
233233
}
234234

235+
fn list_mul(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
236+
arg_check!(
237+
vm,
238+
args,
239+
required = [
240+
(list, Some(vm.ctx.list_type())),
241+
(product, Some(vm.ctx.int_type()))
242+
]
243+
);
244+
245+
let counter = objint::get_value(&product).to_usize().unwrap();
246+
247+
let elements = get_elements(list);
248+
let current_len = elements.len();
249+
let mut new_elements = Vec::with_capacity(counter * current_len);
250+
251+
for _ in 0..counter {
252+
new_elements.extend(elements.clone());
253+
}
254+
255+
Ok(PyObject::new(
256+
PyObjectKind::Sequence {
257+
elements: new_elements,
258+
},
259+
vm.ctx.list_type(),
260+
))
261+
}
262+
235263
pub fn init(context: &PyContext) {
236264
let ref list_type = context.list_type;
237265
context.set_attr(&list_type, "__add__", context.new_rustfunc(list_add));
@@ -252,6 +280,7 @@ pub fn init(context: &PyContext) {
252280
"__setitem__",
253281
context.new_rustfunc(list_setitem),
254282
);
283+
context.set_attr(&list_type, "__mul__", context.new_rustfunc(list_mul));
255284
context.set_attr(&list_type, "__len__", context.new_rustfunc(list_len));
256285
context.set_attr(&list_type, "__new__", context.new_rustfunc(list_new));
257286
context.set_attr(&list_type, "__repr__", context.new_rustfunc(list_repr));

0 commit comments

Comments
 (0)