[PATCH 06/34] alist: Add a function to empty the list
Simon Glass
sjg at chromium.org
Fri Oct 18 01:23:45 CEST 2024
Sometimes it is useful to empty the list without de-allocating any of
the memory used, e.g. when the list will be re-populated immediately
afterwards.
Add a new function for this.
Signed-off-by: Simon Glass <sjg at chromium.org>
---
include/alist.h | 7 +++++++
lib/alist.c | 5 +++++
test/lib/alist.c | 42 ++++++++++++++++++++++++++++++++++++++++++
3 files changed, 54 insertions(+)
diff --git a/include/alist.h b/include/alist.h
index 0090b9c0eb1..c639e42ab7d 100644
--- a/include/alist.h
+++ b/include/alist.h
@@ -274,6 +274,13 @@ bool alist_chk_ptr(const struct alist *lst, const void *ptr);
_pos < alist_end(_lst, typeof(*(_pos))); \
_pos++)
+/**
+ * alist_empty() - Empty an alist
+ *
+ * This removes all entries from the list, without changing the allocated size
+ */
+void alist_empty(struct alist *lst);
+
/**
* alist_init() - Set up a new object list
*
diff --git a/lib/alist.c b/lib/alist.c
index 1a4b4fb9c40..32cd45b0b01 100644
--- a/lib/alist.c
+++ b/lib/alist.c
@@ -41,6 +41,11 @@ void alist_uninit(struct alist *lst)
memset(lst, '\0', sizeof(struct alist));
}
+void alist_empty(struct alist *lst)
+{
+ lst->count = 0;
+}
+
/**
* alist_expand_to() - Expand a list to the given size
*
diff --git a/test/lib/alist.c b/test/lib/alist.c
index 1715a22584c..87135bb3a51 100644
--- a/test/lib/alist.c
+++ b/test/lib/alist.c
@@ -358,6 +358,16 @@ static int lib_test_alist_for_each(struct unit_test_state *uts)
ptr = lst.data;
ut_asserteq_ptr(ptr + 3, alist_end(&lst, struct my_struct));
+ /* empty the list and try again */
+ alist_empty(&lst);
+ ut_asserteq_ptr(ptr, alist_end(&lst, struct my_struct));
+ ut_assertnull(alist_get(&lst, 0, struct my_struct));
+
+ sum = 0;
+ alist_for_each(ptr, &lst)
+ sum += ptr->val;
+ ut_asserteq(0, sum);
+
alist_uninit(&lst);
/* Check for memory leaks */
@@ -366,3 +376,35 @@ static int lib_test_alist_for_each(struct unit_test_state *uts)
return 0;
}
LIB_TEST(lib_test_alist_for_each, 0);
+
+/* Test alist_empty() */
+static int lib_test_alist_empty(struct unit_test_state *uts)
+{
+ struct my_struct data;
+ struct alist lst;
+ ulong start;
+
+ start = ut_check_free();
+
+ ut_assert(alist_init_struct(&lst, struct my_struct));
+ ut_asserteq(0, lst.count);
+ data.val = 1;
+ data.other_val = 0;
+ alist_add(&lst, data);
+ ut_asserteq(1, lst.count);
+ ut_asserteq(4, lst.alloc);
+
+ alist_empty(&lst);
+ ut_asserteq(0, lst.count);
+ ut_asserteq(4, lst.alloc);
+ ut_assertnonnull(lst.data);
+ ut_asserteq(sizeof(data), lst.obj_size);
+
+ alist_uninit(&lst);
+
+ /* Check for memory leaks */
+ ut_assertok(ut_check_delta(start));
+
+ return 0;
+}
+LIB_TEST(lib_test_alist_empty, 0);
--
2.34.1
More information about the U-Boot
mailing list