diff --git a/headers/binary_set.h b/headers/binary_set.h index 1910b93..fef4c80 100644 --- a/headers/binary_set.h +++ b/headers/binary_set.h @@ -165,11 +165,16 @@ static inline void destroy_binary_set(binary_set_s * set, const destroy_binary_s } static inline bool contains_binary_set(const binary_set_s set, const BINARY_SET_DATA_TYPE element) { + if (set.compare) { // uses buildin binary search implmentation if compare function is specified + return bsearch(&element, set.elements, set.size, sizeof(BINARY_SET_DATA_TYPE), set.compare) != NULL; + } + // else custom binary search is used as memcmp takes three arguments as input + // (bsearch requires a 2 argument compare function). IF ONLY NESTED FUNCTION WERE PART OF THE C STANDARD. + BINARY_SET_DATA_TYPE * base = set.elements; for (size_t limit = set.size; limit != 0; limit >>= 1) { BINARY_SET_DATA_TYPE * current_element = base + (limit >> 1); - printf("%d ", current_element->sub_one); - const int cmp = set.compare ? set.compare(&element, current_element) : memcmp(&element, current_element, sizeof(BINARY_SET_DATA_TYPE)); + const int cmp = memcmp(&element, current_element, sizeof(BINARY_SET_DATA_TYPE)); if (cmp == 0) { return true; } @@ -178,7 +183,6 @@ static inline bool contains_binary_set(const binary_set_s set, const BINARY_SET_ limit--; } } - puts("\n"); return false; } diff --git a/test/binary_set/infinite_realloc_binary_set.c b/test/binary_set/infinite_realloc_binary_set.c index 6a5afae..2d3442a 100644 --- a/test/binary_set/infinite_realloc_binary_set.c +++ b/test/binary_set/infinite_realloc_binary_set.c @@ -32,7 +32,9 @@ TEST IRBS_02(void) { binary_set_s united = union_binary_set(set_one, set_two, NULL); for (int i = 0; i < (REALLOC_BINARY_SET_CHUNK - 1) * 3; ++i) { - ASSERTm("[IRBS-ERROR] expected set to contain i", contains_binary_set(united, (BINARY_SET_DATA_TYPE) { .sub_one = i, })); + BINARY_SET_DATA_TYPE element = { 0 }; + element.sub_one = i; + ASSERTm("[IRBS-ERROR] expected set to contain i", contains_binary_set(united, element)); } destroy_binary_set(&united, NULL);