diff --git a/common/list.c b/common/list.c index d57234e3..ffe8b177 100644 --- a/common/list.c +++ b/common/list.c @@ -129,3 +129,18 @@ void list_stable_sort(list_t *list, int compare(const void *a, const void *b)) { list_inplace_sort(list, 0, list->length - 1, compare); } } + +void *list_bsearch(list_t *list, int compare(const void *a, const void *b), const void *data) { + return bsearch(data, list->items, list->length, sizeof(void*), compare); +} + +int list_binary_find(list_t *list, int compare(const void *item, const void *data), const void *data, size_t size) { + if (list->length == 0) { + return -1; + } + void **item = list_bsearch(list, compare, data); + if (item != NULL) + return (item-list->items) / size; + else + return -1; +} diff --git a/include/list.h b/include/list.h index f478b6bb..0e82dba2 100644 --- a/include/list.h +++ b/include/list.h @@ -1,6 +1,8 @@ #ifndef _SWAY_LIST_H #define _SWAY_LIST_H +#include + typedef struct { int capacity; int length; @@ -22,4 +24,9 @@ void list_qsort(list_t *list, int compare(const void *left, const void *right)); int list_seq_find(list_t *list, int compare(const void *item, const void *cmp_to), const void *cmp_to); // stable sort since qsort is not guaranteed to be stable void list_stable_sort(list_t *list, int compare(const void *a, const void *b)); +// binary search +void *list_bsearch(list_t *list, int compare(const void *a, const void *data), const void *data); +// Return index for an item that returns 0 for given compare +// function or -1 if none matches. +int list_binary_find(list_t *list, int compare(const void *item, const void *data), const void *data, size_t size); #endif