// Linear search. // Returns index of element if found, otherwise m->tail. size_t dyn_search(DynArray* m, int x) { size_t i = 0; while (i < m->tail && dyn_get(m, i) != x) { ++i; } return i; }
// Binary search. Assumes the DynArray is sorted!!! // Returns index of element if found, otherwise m->tail. // If there are duplicates, one of them is chosen. size_t dyn_binsearch(DynArray* m, int x) { size_t notfoundindex = m->tail; if (m->tail == 0) { return notfoundindex; } size_t a = 0, b = m->tail - 1; while (a < b) { size_t mid = a + (b-a)/2; // (no overflow) int k = dyn_get(m, mid); if (k < x) { a = mid + 1; } else { b = mid; } } if (dyn_get(m, a) == x) { return a; } return notfoundindex; }
void test_index(DynArray* m, int i, int x) { int* pv = dyn_ptr(m, i); assert(*pv == x); int vv = dyn_get(m, i); assert(vv == x); int lin = dyn_search(m, x); assert(lin == i); int bin = dyn_binsearch(m, x); assert(bin == i); }
// Cached version of the above dyn_get function. static ib_status_t dyn_get_cached( const ib_field_t *f, void *out_value, const void *arg, size_t alen, void *data ) { /* Call the get function */ const char* cval; dyn_get(f, &cval, arg, alen, data); /* Cache the value */ /* Caching does not semantically change value, so we can safely ignore * the constness of f. */ ib_field_make_static((ib_field_t *)f); ib_field_setv((ib_field_t *)f, ib_ftype_nulstr_in(cval)); *reinterpret_cast<const char**>(out_value) = cval; return IB_OK; }