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
parent 0658051996
commit a274a8e5a0
Notes: sideshowbarker 2024-07-19 01:52:36 +09:00
2 changed files with 17 additions and 2 deletions

View file

@ -33,13 +33,13 @@
namespace AK { namespace AK {
template<typename T> 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; return a - b;
} }
template<typename T, typename Compare> 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 (haystack.size() == 0) {
if (nearby_index) if (nearby_index)

View file

@ -146,4 +146,19 @@ TEST_CASE(huge_char_array)
delete[] span.data(); 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) TEST_MAIN(BinarySearch)