AK: Add Span::ends_with()

Originally I added this to use it in Utf16View::ends_with(), but the
final implementation ended up a lot simpler. I chose to keep this anyway
since it mirrors Span::starts_with().
This commit is contained in:
Jelle Raaijmakers 2025-07-23 01:14:24 +02:00 committed by Tim Flynn
commit 54dd45d3f6
Notes: github-actions[bot] 2025-07-24 11:20:08 +00:00
2 changed files with 24 additions and 0 deletions

View file

@ -228,6 +228,14 @@ public:
return TypedTransfer<T>::compare(data(), other.data(), other.size()); return TypedTransfer<T>::compare(data(), other.data(), other.size());
} }
[[nodiscard]] constexpr bool ends_with(ReadonlySpan<T> other) const
{
if (size() < other.size())
return false;
return TypedTransfer<T>::compare(offset_pointer(size() - other.size()), other.data(), other.size());
}
[[nodiscard]] constexpr size_t matching_prefix_length(ReadonlySpan<T> other) const [[nodiscard]] constexpr size_t matching_prefix_length(ReadonlySpan<T> other) const
{ {
auto maximum_length = min(size(), other.size()); auto maximum_length = min(size(), other.size());

View file

@ -152,6 +152,22 @@ TEST_CASE(starts_with)
EXPECT(bytes.starts_with(hey_bytes_u8)); EXPECT(bytes.starts_with(hey_bytes_u8));
} }
TEST_CASE(ends_with)
{
char const* str = "HeyFriends!";
ReadonlyBytes bytes { str, strlen(str) };
char const* str_friends = "Friends!";
ReadonlyBytes friends_bytes { str_friends, strlen(str_friends) };
EXPECT(bytes.ends_with(friends_bytes));
char const* str_nah = "Nah";
ReadonlyBytes nah_bytes { str_nah, strlen(str_nah) };
EXPECT(!bytes.ends_with(nah_bytes));
u8 const dse_array[3] = { 'd', 's', '!' };
ReadonlyBytes dse_bytes_u8 { dse_array, 3 };
EXPECT(bytes.ends_with(dse_bytes_u8));
}
TEST_CASE(contains_slow) TEST_CASE(contains_slow)
{ {
Vector<String> list { "abc"_string, "def"_string, "ghi"_string }; Vector<String> list { "abc"_string, "def"_string, "ghi"_string };