Merge pull request #561 from carlosgp143/contrib/list-contain-element

Add list_contains feature into list.h
This commit is contained in:
Simon Duquennoy 2018-06-01 14:23:23 +02:00 committed by GitHub
commit 2b6b9cc05f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 39 additions and 0 deletions

View File

@ -324,4 +324,26 @@ list_item_next(void *item)
return item == NULL ? NULL : ((struct list *)item)->next;
}
/*---------------------------------------------------------------------------*/
/**
* \brief Check if the list contains an item
* \param list The list that is checked
* \param item An item to look for in the list
* \returns 0 if the list does not contains the item, and 1 otherwise
*
* This function searches for an item in the list and returns
* 0 if the list does not contain the item, and 1 if the item
* is present in the list.
*/
bool
list_contains(list_t list, void *item)
{
struct list *l;
for(l = *list; l != NULL; l = l->next) {
if(item == l) {
return true;
}
}
return false;
}
/*---------------------------------------------------------------------------*/
/** @} */

View File

@ -66,6 +66,8 @@
#ifndef LIST_H_
#define LIST_H_
#include <stdbool.h>
#define LIST_CONCAT2(s1, s2) s1##s2
#define LIST_CONCAT(s1, s2) LIST_CONCAT2(s1, s2)
@ -151,6 +153,8 @@ void list_insert(list_t list, void *previtem, void *newitem);
void * list_item_next(void *item);
bool list_contains(list_t list, void *item);
#endif /* LIST_H_ */
/** @} */

View File

@ -156,6 +156,19 @@ UNIT_TEST(test_list)
UNIT_TEST_ASSERT(tail->next == NULL);
UNIT_TEST_ASSERT(list_length(lst) == 4);
/*
* Check that list contains elements 0, 1, 2, 3
* and not others
* 0 --> 1 --> 2 --> 3 --> NULL
*/
UNIT_TEST_ASSERT(list_contains(lst, &elements[0]));
UNIT_TEST_ASSERT(list_contains(lst, &elements[1]));
UNIT_TEST_ASSERT(list_contains(lst, &elements[2]));
UNIT_TEST_ASSERT(list_contains(lst, &elements[3]));
int i;
for(i=4; i<ELEMENT_COUNT; i++) {
UNIT_TEST_ASSERT(!list_contains(lst, &elements[i]));
}
/*
* Remove the tail
* 0 --> 1 --> 2 --> NULL