From 8a0b75d591f112120c2ee1d5b21625a7700e60d7 Mon Sep 17 00:00:00 2001 From: Daniel Watkins Date: Sun, 5 Aug 2018 15:48:08 -0400 Subject: [PATCH] Implement (positive) stepped slicing for lists --- tests/snippets/3.1.3.2.py | 4 ++++ vm/src/objlist.rs | 24 +++++++++++++++--------- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/tests/snippets/3.1.3.2.py b/tests/snippets/3.1.3.2.py index 243d95e97..2d107e6b2 100644 --- a/tests/snippets/3.1.3.2.py +++ b/tests/snippets/3.1.3.2.py @@ -4,3 +4,7 @@ assert 1 == squares[0] assert 25 == squares[-1] assert [9, 16, 25] == squares[-3:] assert squares == squares[:] + +assert [1, 9, 25] == squares[::2] +assert [4, 16] == squares[1::2] +assert [4] == squares[1:2:2] diff --git a/vm/src/objlist.rs b/vm/src/objlist.rs index 7659e078a..9ed5af55d 100644 --- a/vm/src/objlist.rs +++ b/vm/src/objlist.rs @@ -29,19 +29,25 @@ pub fn get_item(vm: &mut VirtualMachine, l: &Vec, b: PyObjectRef) - &Some(stop) => get_pos(l, stop), &None => l.len() as usize, }; - let step = match step { - //Some(step) => step as usize, - &None => 1 as usize, - _ => unimplemented!("stepped slicing not supported for type {:?}", l), - }; // TODO: we could potentially avoid this copy and use slice - let obj = PyObject::new( + Ok(PyObject::new( PyObjectKind::List { - elements: l[start..stop].to_vec(), + elements: match step { + &None | &Some(1) => l[start..stop].to_vec(), + &Some(num) => { + if num < 0 { + unimplemented!("negative step indexing not yet supported") + }; + l[start..stop] + .iter() + .step_by(num as usize) + .cloned() + .collect() + } + }, }, vm.get_type(), - ); - Ok(obj) + )) } _ => Err(vm.new_exception(format!( "TypeError: indexing type {:?} with index {:?} is not supported (yet?)",