1//===-- Unittests for bsearch ---------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "src/stdlib/bsearch.h"
10
11#include "test/UnitTest/Test.h"
12
13#include <stdlib.h>
14
15static int int_compare(const void *l, const void *r) {
16 int li = *reinterpret_cast<const int *>(l);
17 int ri = *reinterpret_cast<const int *>(r);
18 if (li == ri)
19 return 0;
20 else if (li > ri)
21 return 1;
22 else
23 return -1;
24}
25
26TEST(LlvmLibcBsearchTest, ErrorInputs) {
27 int val = 123;
28 EXPECT_TRUE(LIBC_NAMESPACE::bsearch(nullptr, &val, 1, sizeof(int),
29 int_compare) == nullptr);
30 EXPECT_TRUE(LIBC_NAMESPACE::bsearch(&val, nullptr, 1, sizeof(int),
31 int_compare) == nullptr);
32 EXPECT_TRUE(LIBC_NAMESPACE::bsearch(&val, &val, 0, sizeof(int),
33 int_compare) == nullptr);
34 EXPECT_TRUE(LIBC_NAMESPACE::bsearch(&val, &val, 1, 0, int_compare) ==
35 nullptr);
36}
37
38TEST(LlvmLibcBsearchTest, IntegerArray) {
39 constexpr int ARRAY[25] = {10, 23, 33, 35, 55, 70, 71,
40 100, 110, 123, 133, 135, 155, 170,
41 171, 1100, 1110, 1123, 1133, 1135, 1155,
42 1170, 1171, 11100, 12310};
43 constexpr size_t ARRAY_SIZE = sizeof(ARRAY) / sizeof(int);
44
45 for (size_t s = 1; s <= ARRAY_SIZE; ++s) {
46 for (size_t i = 0; i < s; ++i) {
47 int key = ARRAY[i];
48 void *elem =
49 LIBC_NAMESPACE::bsearch(key: &key, array: ARRAY, array_size: s, elem_size: sizeof(int), compare: int_compare);
50 ASSERT_EQ(*reinterpret_cast<int *>(elem), key);
51 }
52 }
53
54 // Non existent keys
55 for (size_t s = 1; s <= ARRAY_SIZE; ++s) {
56 int key = 5;
57 ASSERT_TRUE(LIBC_NAMESPACE::bsearch(&key, &ARRAY, s, sizeof(int),
58 int_compare) == nullptr);
59
60 key = 125;
61 ASSERT_TRUE(LIBC_NAMESPACE::bsearch(&key, &ARRAY, s, sizeof(int),
62 int_compare) == nullptr);
63
64 key = 136;
65 ASSERT_TRUE(LIBC_NAMESPACE::bsearch(&key, &ARRAY, s, sizeof(int),
66 int_compare) == nullptr);
67 key = 12345;
68 ASSERT_TRUE(LIBC_NAMESPACE::bsearch(&key, &ARRAY, s, sizeof(int),
69 int_compare) == nullptr);
70 }
71}
72
73TEST(LlvmLibcBsearchTest, SameKeyAndArray) {
74 constexpr int ARRAY[5] = {1, 2, 3, 4, 5};
75 constexpr size_t ARRAY_SIZE = sizeof(ARRAY) / sizeof(int);
76 void *elem = LIBC_NAMESPACE::bsearch(key: ARRAY, array: ARRAY, array_size: ARRAY_SIZE, elem_size: sizeof(int),
77 compare: int_compare);
78 EXPECT_EQ(*reinterpret_cast<int *>(elem), ARRAY[0]);
79}
80

source code of libc/test/src/stdlib/bsearch_test.cpp