The sorted list library provides an implementation of the ordered list. Access to the list is not protected. The user function is used for comparing items.
Creating a list
To create a sorted list instance, use the NRF_SORTLIST_DEF macro and provide the identifier and the compare function.
Using the list
Items which can be put into the list must contain the nrf_sortlist_item_t element. CONTAINER_OF() macro should be used to ensure that the nrf_sortlist_item_t element is correctly used.
Sample code for element structure definition:
typedef struct {
uint32_t x;
nrf_sortlist_item_t item;
} item_t;
Example of the compare function:
{
item_t * p_item0 = CONTAINER_OF(p_item0, item_t, item);
item_t * p_item1 = CONTAINER_OF(p_item1, item_t, item);
return (p_item0->x > p_item1->x) ? true : false;
}
Example of sorted list instance definition:
NRF_SORTLIST_DEF(example_list, compare_function);
Example of adding and poping an element into/from the list:
item_t item0, item1;
item0.x = 100;
item1.x = 110;
nrf_sortlist_add(&example_list, &item0.item);
nrf_sortlist_add(&example_list, &item1.item);
item_t * p_item;
p_item = CONTAINER_OF(nrf_sortlist_pop(&example_list), item_t, item);
// p_item points to item1 even though it was later added to the list.
// This happens because the compare function evaluated the elements and reordered them.