From 13cfabd1b265d974e53e03d1d77eac7dc1d000e5 Mon Sep 17 00:00:00 2001 From: Paul Sokolovsky Date: Sun, 2 Feb 2014 03:32:55 +0200 Subject: [PATCH] Implement slicing for lists. --- py/obj.h | 1 + py/objlist.c | 10 +++++++++- tests/basics/list1.py | 4 ++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/py/obj.h b/py/obj.h index 45430d4a1c..bed5103dbd 100644 --- a/py/obj.h +++ b/py/obj.h @@ -396,3 +396,4 @@ typedef struct _mp_obj_classmethod_t { // sequence helpers void mp_seq_multiply(const void *items, uint item_sz, uint len, uint times, void *dest); bool m_seq_get_fast_slice_indexes(machine_uint_t len, mp_obj_t slice, machine_uint_t *begin, machine_uint_t *end); +#define m_seq_copy(dest, src, len, item_sz) memcpy(dest, src, len * sizeof(item_sz)) diff --git a/py/objlist.c b/py/objlist.c index b28ca81279..f3db99a637 100644 --- a/py/objlist.c +++ b/py/objlist.c @@ -136,7 +136,15 @@ static mp_obj_t list_binary_op(int op, mp_obj_t lhs, mp_obj_t rhs) { switch (op) { case RT_BINARY_OP_SUBSCR: { - // list load +#if MICROPY_ENABLE_SLICE + if (MP_OBJ_IS_TYPE(rhs, &slice_type)) { + machine_uint_t start, stop; + assert(m_seq_get_fast_slice_indexes(o->len, rhs, &start, &stop)); + mp_obj_list_t *res = list_new(stop - start); + m_seq_copy(res->items, o->items + start, res->len, mp_obj_t); + return res; + } +#endif uint index = mp_get_index(o->base.type, o->len, rhs); return o->items[index]; } diff --git a/tests/basics/list1.py b/tests/basics/list1.py index 250a12b704..8dc3939dd6 100644 --- a/tests/basics/list1.py +++ b/tests/basics/list1.py @@ -16,3 +16,7 @@ print(x) x += [2, 1] print(x) + +print(x[1:]) +print(x[:-1]) +print(x[2:3])