From 7364af2d8cd72467bbb3bf135b29fae47105b232 Mon Sep 17 00:00:00 2001 From: Paul Sokolovsky Date: Sun, 2 Feb 2014 02:38:22 +0200 Subject: Factor out m_seq_get_fast_slice_indexes() fucntions as sequence helper. Takes slice object and sequence length and computes subsequence indexes for case of slice step=1. --- py/sequence.c | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) (limited to 'py/sequence.c') diff --git a/py/sequence.c b/py/sequence.c index 56718c6f8..1e851a9f8 100644 --- a/py/sequence.c +++ b/py/sequence.c @@ -23,3 +23,33 @@ void mp_seq_multiply(const void *items, uint item_sz, uint len, uint times, void dest = (char*)dest + copy_sz; } } + +bool m_seq_get_fast_slice_indexes(machine_uint_t len, mp_obj_t slice, machine_uint_t *begin, machine_uint_t *end) { + machine_int_t start, stop, step; + mp_obj_slice_get(slice, &start, &stop, &step); + if (step != 1) { + return false; + } + + // Unlike subscription, out-of-bounds slice indexes are never error + if (start < 0) { + start = len + start; + if (start < 0) { + start = 0; + } + } else if (start > len) { + start = len; + } + if (stop <= 0) { + stop = len + stop; + // CPython returns empty sequence in such case + if (stop < 0) { + stop = start; + } + } else if (stop > len) { + stop = len; + } + *begin = start; + *end = stop; + return true; +} -- cgit v1.2.3