summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorThomas Haller <thaller@redhat.com>2023-03-07 10:27:58 +0100
committerThomas Haller <thaller@redhat.com>2023-03-08 15:34:47 +0100
commit4733cf7460dfc4bfc45eff86950f1bdb6e768e5a (patch)
treec34b93d134c7eb1dae185cc2ef7a811871d5cf28
parent84ac0bdf65e373929154a71452d6ffccdc6d8797 (diff)
std-aux: add c_list_is_empty_or_single() helper
Having a list with only one element is often interesting to know. For example, if you are about to unlink an element, you may want to check whether afterwards the list is empty. Add c_list_is_empty_or_single() for that. It is probably more efficient than plain c_list_length_is(list, 1) and also a better name.
-rw-r--r--src/libnm-core-impl/tests/test-general.c8
-rw-r--r--src/libnm-std-aux/c-list-util.h6
2 files changed, 14 insertions, 0 deletions
diff --git a/src/libnm-core-impl/tests/test-general.c b/src/libnm-core-impl/tests/test-general.c
index 8a98265abb..84d9caaeae 100644
--- a/src/libnm-core-impl/tests/test-general.c
+++ b/src/libnm-core-impl/tests/test-general.c
@@ -1417,6 +1417,7 @@ _do_test_c_list_sort(CListSort *elements, guint n_list, gboolean headless)
g_assert(!c_list_is_empty(&head));
g_assert(c_list_length(&head) == n_list);
+ g_assert(c_list_is_empty_or_single(&head) == (n_list <= 1));
el_prev = NULL;
c_list_for_each (iter, &head) {
@@ -1443,6 +1444,10 @@ test_c_list_sort(void)
guint n_list;
guint repeat;
+ g_assert(!c_list_is_linked(NULL));
+ g_assert(c_list_is_empty(NULL));
+ g_assert(c_list_is_empty_or_single(NULL));
+
{
CList head;
@@ -1450,6 +1455,7 @@ test_c_list_sort(void)
c_list_sort(&head, _c_list_sort_cmp, NULL);
g_assert(c_list_length(&head) == 0);
g_assert(c_list_is_empty(&head));
+ g_assert(c_list_is_empty_or_single(&head));
}
elements = g_new0(CListSort, N_ELEMENTS);
@@ -1517,6 +1523,8 @@ _do_test_c_list_insert_sorted(CListSort *elements, guint n_list, bool append_equ
g_assert(c_list_length_is(&head, n_list));
g_assert(!c_list_length_is(&head, n_list + 1));
+ g_assert(c_list_is_empty_or_single(&head) == (n_list <= 1));
+
el_prev = NULL;
c_list_for_each_entry (el, &head, lst) {
if (el_prev) {
diff --git a/src/libnm-std-aux/c-list-util.h b/src/libnm-std-aux/c-list-util.h
index 4800a3cc11..ae2f07ec8c 100644
--- a/src/libnm-std-aux/c-list-util.h
+++ b/src/libnm-std-aux/c-list-util.h
@@ -42,6 +42,12 @@ c_list_length_is(const CList *list, unsigned long check_len)
return n == check_len;
}
+static inline int
+c_list_is_empty_or_single(const CList *list)
+{
+ return !list || (list->next->next == list);
+}
+
#define c_list_for_each_prev(_iter, _list) \
for (_iter = (_list)->prev; (_iter) != (_list); _iter = (_iter)->prev)