diff --git a/AK/BinarySearch.h b/AK/BinarySearch.h index 6994b946005..1fafb777fe4 100644 --- a/AK/BinarySearch.h +++ b/AK/BinarySearch.h @@ -33,13 +33,13 @@ namespace AK { template -int integral_compare(const typename RemoveConst::Type& a, const typename RemoveConst::Type& b) +constexpr int integral_compare(const typename RemoveConst::Type& a, const typename RemoveConst::Type& b) { return a - b; } template -T* binary_search(Span haystack, const typename RemoveConst::Type& needle, Compare compare = integral_compare, size_t* nearby_index = nullptr) +constexpr T* binary_search(Span haystack, const typename RemoveConst::Type& needle, Compare compare = integral_compare, size_t* nearby_index = nullptr) { if (haystack.size() == 0) { if (nearby_index) diff --git a/AK/Tests/TestBinarySearch.cpp b/AK/Tests/TestBinarySearch.cpp index 6e27fd1c602..91d9d3855ef 100644 --- a/AK/Tests/TestBinarySearch.cpp +++ b/AK/Tests/TestBinarySearch.cpp @@ -146,4 +146,19 @@ TEST_CASE(huge_char_array) delete[] span.data(); } +TEST_CASE(constexpr_array_search) +{ + constexpr Array array = { 1, 17, 42 }; + + constexpr auto test1 = *binary_search(array.span(), 1, AK::integral_compare); + constexpr auto test2 = *binary_search(array.span(), 17, AK::integral_compare); + constexpr auto test3 = *binary_search(array.span(), 42, AK::integral_compare); + constexpr auto test4 = binary_search(array.span(), 99, AK::integral_compare); + + 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)