BinarySearch: constexpr support

Problem:
- It is not possible to perform a binary search at compile-time
  because `binary_search` is not `constexpr`-aware.

Solution:
- Add `constexpr` support.
This commit is contained in:
Lenny Maiorani 2020-10-13 18:30:35 -04:00 committed by Andreas Kling
commit a274a8e5a0
Notes: sideshowbarker 2024-07-19 01:52:36 +09:00
2 changed files with 17 additions and 2 deletions

View file

@ -146,4 +146,19 @@ TEST_CASE(huge_char_array)
delete[] span.data();
}
TEST_CASE(constexpr_array_search)
{
constexpr Array<int, 3> array = { 1, 17, 42 };
constexpr auto test1 = *binary_search(array.span(), 1, AK::integral_compare<int>);
constexpr auto test2 = *binary_search(array.span(), 17, AK::integral_compare<int>);
constexpr auto test3 = *binary_search(array.span(), 42, AK::integral_compare<int>);
constexpr auto test4 = binary_search(array.span(), 99, AK::integral_compare<int>);
static_assert(test1 == 1, "Binary search should find value at compile-time.");
static_assert(test2 == 17, "Binary search should find value at compile-time.");
static_assert(test3 == 42, "Binary search should find value at compile-time.");
static_assert(test4 == nullptr, "Binary search should return nullptr for missing value at compile-time.");
}
TEST_MAIN(BinarySearch)