Skip to content

Commit

Permalink
BinarySearch: constexpr support
Browse files Browse the repository at this point in the history
Problem:
- It is not possible to perform a binary search at compile-time
  because `binary_search` is not `constexpr`-aware.

Solution:
- Add `constexpr` support.
  • Loading branch information
ldm5180 authored and awesomekling committed Oct 17, 2020
1 parent 0658051 commit a274a8e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
4 changes: 2 additions & 2 deletions AK/BinarySearch.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@
namespace AK {

template<typename T>
int integral_compare(const typename RemoveConst<T>::Type& a, const typename RemoveConst<T>::Type& b)
constexpr int integral_compare(const typename RemoveConst<T>::Type& a, const typename RemoveConst<T>::Type& b)
{
return a - b;
}

template<typename T, typename Compare>
T* binary_search(Span<T> haystack, const typename RemoveConst<T>::Type& needle, Compare compare = integral_compare, size_t* nearby_index = nullptr)
constexpr T* binary_search(Span<T> haystack, const typename RemoveConst<T>::Type& needle, Compare compare = integral_compare, size_t* nearby_index = nullptr)
{
if (haystack.size() == 0) {
if (nearby_index)
Expand Down
15 changes: 15 additions & 0 deletions AK/Tests/TestBinarySearch.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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)

0 comments on commit a274a8e

Please sign in to comment.