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.
This commit is contained in:
Thomas Haller 2023-03-07 10:27:58 +01:00
parent 84ac0bdf65
commit 4733cf7460
No known key found for this signature in database
GPG key ID: 29C2366E4DFC5728
2 changed files with 14 additions and 0 deletions

View file

@ -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) {

View file

@ -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)