# HG changeset patch # User Mike Becker # Date 1726607943 -7200 # Node ID 878a450e79bd6c96594edf42e9db14ab781bb85d # Parent d375d8056262c3cb9cedf7af5e5591710ca699ed fixes incorrect result from cx_array_binary_search() when searched element is smaller than the entire array relates to #424 diff -r d375d8056262 -r 878a450e79bd src/array_list.c --- a/src/array_list.c Tue Sep 17 23:11:17 2024 +0200 +++ b/src/array_list.c Tue Sep 17 23:19:03 2024 +0200 @@ -251,7 +251,9 @@ // check the first array element result = cmp_func(elem, array); - if (result <= 0) { + if (result < 0) { + return size; + } else if (result == 0) { return 0; } diff -r d375d8056262 -r 878a450e79bd src/cx/array_list.h --- a/src/cx/array_list.h Tue Sep 17 23:11:17 2024 +0200 +++ b/src/cx/array_list.h Tue Sep 17 23:19:03 2024 +0200 @@ -300,6 +300,7 @@ * * In other words, this function returns the index of the largest element * in \p arr that is less or equal to \p elem with respect to \p cmp_func. + * When no such element exists, \p size is returned. * * If \p elem is contained in the array, this is identical to * #cx_array_binary_search(). @@ -312,7 +313,7 @@ * @param elem_size the size of one element * @param elem the element to find * @param cmp_func the compare function - * @return the index of the closest element in the array + * @return the index of the largest upper bound, or \p size */ size_t cx_array_binary_search_inf( void const *arr, diff -r d375d8056262 -r 878a450e79bd tests/test_list.c --- a/tests/test_list.c Tue Sep 17 23:11:17 2024 +0200 +++ b/tests/test_list.c Tue Sep 17 23:19:03 2024 +0200 @@ -173,6 +173,12 @@ s = 69; CX_TEST_ASSERT(11 == cx_array_binary_search_inf(array, 18, sizeof(int), &s, cx_cmp_int)); CX_TEST_ASSERT(18 == cx_array_binary_search(array, 18, sizeof(int), &s, cx_cmp_int)); + s = 95; + CX_TEST_ASSERT(17 == cx_array_binary_search_inf(array, 18, sizeof(int), &s, cx_cmp_int)); + CX_TEST_ASSERT(18 == cx_array_binary_search(array, 18, sizeof(int), &s, cx_cmp_int)); + s = 30; + CX_TEST_ASSERT(18 == cx_array_binary_search_inf(array, 18, sizeof(int), &s, cx_cmp_int)); + CX_TEST_ASSERT(18 == cx_array_binary_search(array, 18, sizeof(int), &s, cx_cmp_int)); } }