1 //===-- Unittests for bsearch ---------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "src/stdlib/bsearch.h"
11 #include "test/UnitTest/Test.h"
15 static 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
);
26 TEST(LlvmLibcBsearchTest
, ErrorInputs
) {
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
) ==
38 TEST(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);
45 for (size_t s
= 1; s
<= ARRAY_SIZE
; ++s
) {
46 for (size_t i
= 0; i
< s
; ++i
) {
49 LIBC_NAMESPACE::bsearch(&key
, ARRAY
, s
, sizeof(int), int_compare
);
50 ASSERT_EQ(*reinterpret_cast<int *>(elem
), key
);
55 for (size_t s
= 1; s
<= ARRAY_SIZE
; ++s
) {
57 ASSERT_TRUE(LIBC_NAMESPACE::bsearch(&key
, &ARRAY
, s
, sizeof(int),
58 int_compare
) == nullptr);
61 ASSERT_TRUE(LIBC_NAMESPACE::bsearch(&key
, &ARRAY
, s
, sizeof(int),
62 int_compare
) == nullptr);
65 ASSERT_TRUE(LIBC_NAMESPACE::bsearch(&key
, &ARRAY
, s
, sizeof(int),
66 int_compare
) == nullptr);
68 ASSERT_TRUE(LIBC_NAMESPACE::bsearch(&key
, &ARRAY
, s
, sizeof(int),
69 int_compare
) == nullptr);
73 TEST(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(ARRAY
, ARRAY
, ARRAY_SIZE
, sizeof(int),
78 EXPECT_EQ(*reinterpret_cast<int *>(elem
), ARRAY
[0]);