From e49f425e43800b35fc7172d7f121b890439b69a8 Mon Sep 17 00:00:00 2001 From: jf-home Date: Wed, 30 Apr 2025 00:17:59 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=87=BD=E6=95=B0=E6=B3=A8?= =?UTF-8?q?=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/list.c | 17 ++++++++++++++++- test/test_list.c | 12 +++++++++--- 2 files changed, 25 insertions(+), 4 deletions(-) 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);