| 1 |
// Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 |
// SPDX-License-Identifier: LGPL-2.1-or-later |
| 3 |
|
| 4 |
#include <stdio.h> |
| 5 |
#include "../binary_search.h" |
| 6 |
|
| 7 |
#suite binary_search |
| 8 |
|
| 9 |
#test-loop(0, 6) binary_search_ge_basic |
| 10 |
{ |
| 11 |
const int arr[] = { 10, 20, 30, 40, 50 }; |
| 12 |
ck_assert_uint_eq(binary_search_ge(arr, _i, &(int){5}, scalar_less), 0); |
| 13 |
for (int i = 1; i <= _i; i++) { |
| 14 |
ck_assert_uint_eq(binary_search_ge(arr, _i, &(int){i * 10}, |
| 15 |
scalar_less), i - 1); |
| 16 |
ck_assert_uint_eq(binary_search_ge(arr, _i, &(int){i * 10 + 5}, |
| 17 |
scalar_less), i); |
| 18 |
} |
| 19 |
} |
| 20 |
|
| 21 |
#test binary_search_ge_duplicates |
| 22 |
{ |
| 23 |
const int arr[] = { 10, 10, 10 }; |
| 24 |
ck_assert_uint_eq(binary_search_ge(arr, 3, &(int){10}, scalar_less), 0); |
| 25 |
} |
| 26 |
|
| 27 |
#test binary_search_ge_custom_less |
| 28 |
{ |
| 29 |
const struct { |
| 30 |
int value; |
| 31 |
const char *str; |
| 32 |
} arr[] = { |
| 33 |
{ 10, "ten" }, |
| 34 |
{ 20, "twenty" }, |
| 35 |
}; |
| 36 |
#define my_less(a, b) ((a)->value < *(b)) |
| 37 |
ck_assert_uint_eq(binary_search_ge(arr, 2, &(int){20}, my_less), 1); |
| 38 |
#undef my_less |
| 39 |
} |
| 40 |
|
| 41 |
#test-loop(0, 6) binary_search_gt_basic |
| 42 |
{ |
| 43 |
const int arr[] = { 10, 20, 30, 40, 50 }; |
| 44 |
ck_assert_uint_eq(binary_search_gt(arr, _i, &(int){5}, scalar_less), 0); |
| 45 |
for (int i = 1; i <= _i; i++) { |
| 46 |
ck_assert_uint_eq(binary_search_gt(arr, _i, &(int){i * 10}, |
| 47 |
scalar_less), i); |
| 48 |
ck_assert_uint_eq(binary_search_gt(arr, _i, &(int){i * 10 + 5}, |
| 49 |
scalar_less), i); |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
#test binary_search_gt_duplicates |
| 54 |
{ |
| 55 |
const int arr[] = { 10, 10, 10 }; |
| 56 |
ck_assert_uint_eq(binary_search_gt(arr, 3, &(int){10}, scalar_less), 3); |
| 57 |
} |
| 58 |
|
| 59 |
#test binary_search_gt_custom_less |
| 60 |
{ |
| 61 |
const struct { |
| 62 |
int value; |
| 63 |
const char *str; |
| 64 |
} arr[] = { |
| 65 |
{ 10, "ten" }, |
| 66 |
{ 20, "twenty" }, |
| 67 |
}; |
| 68 |
#define my_less(a, b) (*(a) < (b)->value) |
| 69 |
ck_assert_uint_eq(binary_search_gt(arr, 2, &(int){20}, my_less), 2); |
| 70 |
#undef my_less |
| 71 |
} |