Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / libc / test / src / stdlib / bsearch_test.cpp
blob689145806ba8d3bd2da2040e4ac70451f5e0cc85
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 //===----------------------------------------------------------------------===//
9 #include "src/stdlib/bsearch.h"
11 #include "test/UnitTest/Test.h"
13 #include <stdlib.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);
18 if (li == ri)
19 return 0;
20 else if (li > ri)
21 return 1;
22 else
23 return -1;
26 TEST(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);
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) {
47 int key = ARRAY[i];
48 void *elem =
49 LIBC_NAMESPACE::bsearch(&key, ARRAY, s, sizeof(int), int_compare);
50 ASSERT_EQ(*reinterpret_cast<int *>(elem), key);
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);
60 key = 125;
61 ASSERT_TRUE(LIBC_NAMESPACE::bsearch(&key, &ARRAY, s, sizeof(int),
62 int_compare) == nullptr);
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);
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),
77 int_compare);
78 EXPECT_EQ(*reinterpret_cast<int *>(elem), ARRAY[0]);