Function SDL_bsearch_r

pub unsafe extern "C" fn SDL_bsearch_r(
    key: *const c_void,
    base: *const c_void,
    nmemb: usize,
    size: usize,
    compare: Option<unsafe extern "C" fn(_: *mut c_void, _: *const c_void, _: *const c_void) -> i32>,
    userdata: *mut c_void,
) -> *mut c_void
Available on crate feature dep_sdl3 only.
Expand description

Perform a binary search on a previously sorted array, passing a userdata pointer to the compare function.

For example:

typedef enum {
    sort_increasing,
    sort_decreasing,
} sort_method;

typedef struct {
    int key;
    const char *string;
} data;

int SDLCALL compare(const void *userdata, const void *a, const void *b)
{
    sort_method method = (sort_method)(uintptr_t)userdata;
    const data *A = (const data *)a;
    const data *B = (const data *)b;

    if (A->key < B->key) {
        return (method == sort_increasing) ? -1 : 1;
    } else if (B->key < A->key) {
        return (method == sort_increasing) ? 1 : -1;
    } else {
        return 0;
    }
}

data values[] = {
    { 1, "first" }, { 2, "second" }, { 3, "third" }
};
data key = { 2, NULL };

data *result = SDL_bsearch_r(&key, values, SDL_arraysize(values), sizeof(values[0]), compare, (const void *)(uintptr_t)sort_increasing);

§Parameters

  • key: a pointer to a key equal to the element being searched for.
  • base: a pointer to the start of the array.
  • nmemb: the number of elements in the array.
  • size: the size of the elements in the array.
  • compare: a function used to compare elements in the array.
  • userdata: a pointer to pass to the compare function.

§Return value

Returns a pointer to the matching element in the array, or NULL if not found.

§Thread safety

It is safe to call this function from any thread.

§Availability

This function is available since SDL 3.2.0.

§See also