diff --git a/AK/Array.h b/AK/Array.h index 3bb11998a3..52ffa5560e 100644 --- a/AK/Array.h +++ b/AK/Array.h @@ -7,6 +7,7 @@ #pragma once #include +#include #include #include #include @@ -119,6 +120,20 @@ struct Array { return value; } + bool contains_slow(T const& value) const + { + return first_index_of(value).has_value(); + } + + Optional first_index_of(T const& value) const + { + for (size_t i = 0; i < Size; ++i) { + if (__data[i] == value) + return i; + } + return {}; + } + Conditional, T[Size]> __data; }; diff --git a/Tests/AK/TestArray.cpp b/Tests/AK/TestArray.cpp index 12aefe5455..24c687fc27 100644 --- a/Tests/AK/TestArray.cpp +++ b/Tests/AK/TestArray.cpp @@ -28,3 +28,21 @@ TEST_CASE(compile_time_iterable) constexpr Array array = { 0, 1, 2, 3, 4, 5, 6, 7 }; static_assert(constexpr_sum(array) == 28); } + +TEST_CASE(contains_slow) +{ + constexpr Array array = { 0, 1, 2, 3, 4, 5, 6, 7 }; + EXPECT(array.contains_slow(0)); + EXPECT(array.contains_slow(4)); + EXPECT(array.contains_slow(7)); + EXPECT(!array.contains_slow(42)); +} + +TEST_CASE(first_index_of) +{ + constexpr Array array = { 0, 1, 2, 3, 4, 5, 6, 7 }; + EXPECT(array.first_index_of(0) == 0u); + EXPECT(array.first_index_of(4) == 4u); + EXPECT(array.first_index_of(7) == 7u); + EXPECT(!array.first_index_of(42).has_value()); +}