Skip to content

Commit e8b8082

Browse files
pks-tgitster
authored andcommitted
reftable/basics: improve binsearch() test
The `binsearch()` test is somewhat weird in that it doesn't explicitly spell out its expectations. Instead it does so in a rather ad-hoc way with some hard-to-understand computations. Refactor the test to spell out the needle as well as expected index for all testcases. This refactoring highlights that the `binsearch_func()` is written somewhat weirdly to find the first integer smaller than the needle, not smaller or equal to it. Adjust the function accordingly. While at it, rename the callback function to better convey its meaning. Signed-off-by: Patrick Steinhardt <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 3e7b36d commit e8b8082

File tree

1 file changed

+31
-24
lines changed

1 file changed

+31
-24
lines changed

reftable/basics_test.c

Lines changed: 31 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -12,40 +12,47 @@ license that can be found in the LICENSE file or at
1212
#include "test_framework.h"
1313
#include "reftable-tests.h"
1414

15-
struct binsearch_args {
16-
int key;
17-
int *arr;
15+
struct integer_needle_lesseq_args {
16+
int needle;
17+
int *haystack;
1818
};
1919

20-
static int binsearch_func(size_t i, void *void_args)
20+
static int integer_needle_lesseq(size_t i, void *_args)
2121
{
22-
struct binsearch_args *args = void_args;
23-
24-
return args->key < args->arr[i];
22+
struct integer_needle_lesseq_args *args = _args;
23+
return args->needle <= args->haystack[i];
2524
}
2625

2726
static void test_binsearch(void)
2827
{
29-
int arr[] = { 2, 4, 6, 8, 10 };
30-
size_t sz = ARRAY_SIZE(arr);
31-
struct binsearch_args args = {
32-
.arr = arr,
28+
int haystack[] = { 2, 4, 6, 8, 10 };
29+
struct {
30+
int needle;
31+
size_t expected_idx;
32+
} testcases[] = {
33+
{-9000, 0},
34+
{-1, 0},
35+
{0, 0},
36+
{2, 0},
37+
{3, 1},
38+
{4, 1},
39+
{7, 3},
40+
{9, 4},
41+
{10, 4},
42+
{11, 5},
43+
{9000, 5},
3344
};
45+
size_t i = 0;
3446

35-
int i = 0;
36-
for (i = 1; i < 11; i++) {
37-
size_t res;
38-
39-
args.key = i;
40-
res = binsearch(sz, &binsearch_func, &args);
47+
for (i = 0; i < ARRAY_SIZE(testcases); i++) {
48+
struct integer_needle_lesseq_args args = {
49+
.haystack = haystack,
50+
.needle = testcases[i].needle,
51+
};
52+
size_t idx;
4153

42-
if (res < sz) {
43-
EXPECT(args.key < arr[res]);
44-
if (res > 0)
45-
EXPECT(args.key >= arr[res - 1]);
46-
} else {
47-
EXPECT(args.key == 10 || args.key == 11);
48-
}
54+
idx = binsearch(ARRAY_SIZE(haystack), &integer_needle_lesseq, &args);
55+
EXPECT(idx == testcases[i].expected_idx);
4956
}
5057
}
5158

0 commit comments

Comments
 (0)