sequence: add g_sequence_is_empty()

This function provides an O(1) check to determine if a sequence is empty.
Compare this to the two following alternatives to perform the same check.

O(h):  if (0 == g_sequence_get_length (seq))
O(2h): if (g_sequence_get_begin_iter(seq) == g_sequence_get_end_iter(seq))

Where `h' is the height of the tree.

https://bugzilla.gnome.org/show_bug.cgi?id=756316
This commit is contained in:
Christian Hergert 2015-10-15 12:54:09 -07:00
parent 0b84596f6e
commit 8fccf8e4e3
3 changed files with 48 additions and 0 deletions

View File

@ -1243,6 +1243,26 @@ g_sequence_get_length (GSequence *seq)
return node_get_length (seq->end_node) - 1;
}
/**
* g_sequence_is_empty:
* @seq: a #GSequence
*
* Returns %TRUE if the sequence contains zero items.
*
* This function is functionally identical to checking the result of
* g_sequence_get_length() being equal to zero. However this function is
* implemented in O(1) running time.
*
* Returns: %TRUE if the sequence is empty, otherwise %FALSE.
*
* Since: 2.48
*/
gboolean
g_sequence_is_empty (GSequence *seq)
{
return (seq->end_node->parent == NULL) && (seq->end_node->left == NULL);
}
/**
* g_sequence_get_end_iter:
* @seq: a #GSequence

View File

@ -59,6 +59,8 @@ GLIB_AVAILABLE_IN_ALL
void g_sequence_sort_iter (GSequence *seq,
GSequenceIterCompareFunc cmp_func,
gpointer cmp_data);
GLIB_AVAILABLE_IN_2_48
gboolean g_sequence_is_empty (GSequence *seq);
/* Getting iters */

View File

@ -1356,6 +1356,31 @@ test_stable_sort (void)
g_sequence_free (seq);
}
static void
test_empty (void)
{
GSequence *seq;
int i;
seq = g_sequence_new (NULL);
g_assert_cmpint (TRUE, ==, g_sequence_is_empty (seq));
for (i = 0; i < 1000; i++)
{
g_sequence_append (seq, GINT_TO_POINTER (i));
g_assert_false (g_sequence_is_empty (seq));
}
for (i = 0; i < 1000; i++)
{
GSequenceIter *end = g_sequence_get_end_iter (seq);
g_assert_false (g_sequence_is_empty (seq));
g_sequence_remove (g_sequence_iter_prev (end));
}
g_assert_true (g_sequence_is_empty (seq));
}
int
main (int argc,
char **argv)
@ -1371,6 +1396,7 @@ main (int argc,
g_test_add_func ("/sequence/iter-move", test_iter_move);
g_test_add_func ("/sequence/insert-sorted-non-pointer", test_insert_sorted_non_pointer);
g_test_add_func ("/sequence/stable-sort", test_stable_sort);
g_test_add_func ("/sequence/is_empty", test_empty);
/* Regression tests */
for (i = 0; i < G_N_ELEMENTS (seeds); ++i)