1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-25 05:37:43 +00:00

AK: Fix overflow and mixed-signedness issues in binary_search() (#2961)

This commit is contained in:
Muhammad Zahalqa 2020-08-02 22:10:35 +03:00 committed by GitHub
parent 2242f69cd6
commit 615ba0f368
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 57 additions and 8 deletions

View file

@ -27,7 +27,9 @@
#include <AK/TestSuite.h>
#include <AK/BinarySearch.h>
#include <AK/Span.h>
#include <cstring>
#include <new>
TEST_CASE(vector_ints)
{
@ -106,4 +108,42 @@ TEST_CASE(no_elements)
EXPECT_EQ(test1, nullptr);
}
TEST_CASE(huge_char_array)
{
const size_t N = 2147483680;
Bytes span { new (std::nothrow) u8[N], N };
EXPECT(span.data() != nullptr);
for (size_t i = 0; i < span.size(); ++i)
span[i] = 'a';
size_t index = N - 1;
for (u8 c = 'z'; c > 'b'; --c)
span[index--] = c;
EXPECT_EQ(span[N - 1], 'z');
const u8 a = 'a';
auto where = binary_search(span, a, AK::integral_compare<u8>);
EXPECT(where != nullptr);
EXPECT_EQ(*where, 'a');
const u8 z = 'z';
where = binary_search(span, z, AK::integral_compare<u8>);
EXPECT(where != nullptr);
EXPECT_EQ(*where, 'z');
size_t near = 0;
const u8 tilde = '~';
where = binary_search(span, tilde, AK::integral_compare<u8>, &near);
EXPECT_EQ(where, nullptr);
EXPECT_EQ(near, N - 1);
const u8 b = 'b';
where = binary_search(span, b, AK::integral_compare<u8>, &near);
EXPECT_EQ(where, nullptr);
EXPECT_EQ(near, N - ('z' - b + 1));
delete[] span.data();
}
TEST_MAIN(BinarySearch)