diff --git a/src/list.c b/src/list.c index 640fab0..4c3929c 100644 --- a/src/list.c +++ b/src/list.c @@ -189,6 +189,21 @@ static void list_print(struct _list* self) } } +/** + * @brief list slice + * if index < 0, from the end of list. for example: + * list[-1] is the last element in list. + * + * @param self + * @param start start index + * @param end end index + * @param step step, if step < 0, return a reverse list. + * @return struct _list* + * a copy of the list, from start to end, step by step. + * if step < 0, return a reverse list. + * if step > 0, return a forward list. + * if step == 0, return NULL. + */ struct _list* list_slice(struct _list *self, int start, int end, int step) { assert(self != NULL); @@ -260,7 +275,7 @@ struct _list* list_slice(struct _list *self, int start, int end, int step) list->insert(list, 0, (char*)self->obj + i * self->_obj_size); } } - + return list; } diff --git a/test/test_list.c b/test/test_list.c index aa450d3..6be19b1 100644 --- a/test/test_list.c +++ b/test/test_list.c @@ -440,14 +440,20 @@ static void test_list_slice(void) } // python: list[0:] -> [] - list2 = list->slice(list, 0, 0, 1); // if start == end - TEST_ASSERT_NULL(list2); - list2 = list->slice(list, 1, 5, 0); // if step == 0 TEST_ASSERT_NULL(list2); + list2 = list->slice(list, 0, 0, 1); // if start == end + TEST_ASSERT_NOT_NULL(list2); + TEST_ASSERT_TRUE(list2->empty(list2)); + list2 = list->slice(list, 1, 5, -1); // if start < end && step < 0 TEST_ASSERT_NULL(list2); + TEST_ASSERT_TRUE(list2->empty(list2)); + + list2 = list->slice(list, 5, 1, 1); // if start > end && step > 0 + TEST_ASSERT_NULL(list2); + TEST_ASSERT_TRUE(list2->empty(list2)); // python: list[0:] list2 = list->slice(list, 0, len, 1);