diff --git a/include/libssh/misc.h b/include/libssh/misc.h index 128e2ba9..6aaeee7c 100644 --- a/include/libssh/misc.h +++ b/include/libssh/misc.h @@ -54,6 +54,7 @@ struct ssh_list *ssh_list_new(void); void ssh_list_free(struct ssh_list *list); struct ssh_iterator *ssh_list_get_iterator(const struct ssh_list *list); struct ssh_iterator *ssh_list_find(const struct ssh_list *list, void *value); +size_t ssh_list_count(const struct ssh_list *list); int ssh_list_append(struct ssh_list *list, const void *data); int ssh_list_prepend(struct ssh_list *list, const void *data); void ssh_list_remove(struct ssh_list *list, struct ssh_iterator *iterator); diff --git a/src/misc.c b/src/misc.c index 9f424281..9817bbfc 100644 --- a/src/misc.c +++ b/src/misc.c @@ -397,6 +397,25 @@ struct ssh_iterator *ssh_list_find(const struct ssh_list *list, void *value){ return NULL; } +/** + * @brief Get the number of elements in the list + * + * @param[in] list The list to count. + * + * @return The number of elements in the list. + */ +size_t ssh_list_count(const struct ssh_list *list) +{ + struct ssh_iterator *it = NULL; + int count = 0; + + for (it = ssh_list_get_iterator(list); it != NULL ; it = it->next) { + count++; + } + + return count; +} + static struct ssh_iterator *ssh_iterator_new(const void *data){ struct ssh_iterator *iterator=malloc(sizeof(struct ssh_iterator)); if(!iterator) diff --git a/tests/unittests/torture_list.c b/tests/unittests/torture_list.c index 0b15fae8..c16155f9 100644 --- a/tests/unittests/torture_list.c +++ b/tests/unittests/torture_list.c @@ -17,6 +17,8 @@ static void torture_ssh_list_new(void **state) { assert_true(xlist->root == NULL); assert_true(xlist->end == NULL); + assert_int_equal(ssh_list_count(xlist), 0); + ssh_list_free(xlist); } @@ -46,6 +48,8 @@ static void torture_ssh_list_append(void **state) { assert_string_equal((const char *) xlist->root->next->next->data, "item3"); assert_string_equal((const char *) xlist->end->data, "item3"); + assert_int_equal(ssh_list_count(xlist), 3); + ssh_list_free(xlist); } @@ -75,6 +79,8 @@ static void torture_ssh_list_prepend(void **state) { assert_string_equal((const char *) xlist->root->next->next->data, "item2"); assert_string_equal((const char *) xlist->end->data, "item2"); + assert_int_equal(ssh_list_count(xlist), 3); + ssh_list_free(xlist); }