array: Add array_bsearch function
This commit is contained in:
@@ -419,6 +419,56 @@ void array_sort(array_t *array, int (*cmp)(const void*,const void*,void*),
|
||||
}
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
/** the array */
|
||||
array_t *array;
|
||||
/** the key */
|
||||
const void *key;
|
||||
/** comparison function */
|
||||
int (*cmp)(const void*,const void*);
|
||||
} bsearch_data_t;
|
||||
|
||||
static int search_elements(const void *a, const void *b)
|
||||
{
|
||||
bsearch_data_t *data = (bsearch_data_t*)a;
|
||||
|
||||
if (data->array->esize)
|
||||
{
|
||||
return data->cmp(data->key, b);
|
||||
}
|
||||
return data->cmp(data->key, *(void**)b);
|
||||
}
|
||||
|
||||
int array_bsearch(array_t *array, const void *key,
|
||||
int (*cmp)(const void*,const void*), void *out)
|
||||
{
|
||||
int idx = -1;
|
||||
|
||||
if (array)
|
||||
{
|
||||
bsearch_data_t data = {
|
||||
.array = array,
|
||||
.key = key,
|
||||
.cmp = cmp,
|
||||
};
|
||||
void *start, *item;
|
||||
|
||||
start = array->data + get_size(array, array->head);
|
||||
|
||||
item = bsearch(&data, start, array->count, get_size(array, 1),
|
||||
search_elements);
|
||||
if (item)
|
||||
{
|
||||
if (out)
|
||||
{
|
||||
memcpy(out, item, get_size(array, 1));
|
||||
}
|
||||
idx = (item - start) / get_size(array, 1);
|
||||
}
|
||||
}
|
||||
return idx;
|
||||
}
|
||||
|
||||
void array_invoke(array_t *array, array_callback_t cb, void *user)
|
||||
{
|
||||
if (array)
|
||||
|
||||
@@ -185,6 +185,31 @@ bool array_remove(array_t *array, int idx, void *data);
|
||||
void array_sort(array_t *array, int (*cmp)(const void*,const void*,void*),
|
||||
void *user);
|
||||
|
||||
/**
|
||||
* Binary search of a sorted array.
|
||||
*
|
||||
* The array should be sorted in ascending order according to the given
|
||||
* comparison function.
|
||||
*
|
||||
* The comparison function must return an integer less than, equal to, or
|
||||
* greater than zero if the first argument (the key) is considered to be
|
||||
* respectively less than, equal to, or greater than the second.
|
||||
*
|
||||
* If there are multiple elements that match the key it is not specified which
|
||||
* element is returned.
|
||||
*
|
||||
* The comparison function receives the key object and a pointer to an array
|
||||
* element (esize != 0) or an actual pointer (esize = 0).
|
||||
*
|
||||
* @param array array to search, or NULL
|
||||
* @param key key to search for
|
||||
* @param cmp comparison function
|
||||
* @param data data to copy element to, or NULL
|
||||
* @return index of the element if found, -1 if not
|
||||
*/
|
||||
int array_bsearch(array_t *array, const void *key,
|
||||
int (*cmp)(const void*,const void*), void *data);
|
||||
|
||||
/**
|
||||
* Invoke a callback for all array members.
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user