From d32e5501be0d3407fed01f76c65f4c90b7c3604e Mon Sep 17 00:00:00 2001 From: Padraic Fanning Date: Thu, 25 Feb 2021 15:53:50 -0500 Subject: [PATCH] Add optional arguments to list.index() More or less directly translated from the CPython implementation. --- vm/src/builtins/list.rs | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/vm/src/builtins/list.rs b/vm/src/builtins/list.rs index c2314e5e2..a2ac44184 100644 --- a/vm/src/builtins/list.rs +++ b/vm/src/builtins/list.rs @@ -271,8 +271,35 @@ impl PyList { } #[pymethod] - fn index(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { - for (index, element) in self.borrow_value().clone().iter().enumerate() { + fn index( + &self, + needle: PyObjectRef, + start: OptionalArg, + stop: OptionalArg, + vm: &VirtualMachine, + ) -> PyResult { + let mut start = start.into_option().unwrap_or(0); + if start < 0 { + start += self.borrow_value().len() as isize; + if start < 0 { + start = 0; + } + } + let mut stop = stop.into_option().unwrap_or(isize::MAX); + if stop < 0 { + stop += self.borrow_value().len() as isize; + if stop < 0 { + stop = 0; + } + } + for (index, element) in self + .borrow_value() + .clone() + .iter() + .enumerate() + .take(stop as usize) + .skip(start as usize) + { if vm.identical_or_equal(element, &needle)? { return Ok(index); }