From 24bc674d94c56d9fc6ac06f442bcf23d8f2db14f Mon Sep 17 00:00:00 2001 From: Shannon Booth Date: Mon, 30 Dec 2019 01:44:30 +1300 Subject: [PATCH] AK: Add StringView::ends_with function --- AK/StringView.cpp | 11 +++++++++++ AK/StringView.h | 1 + AK/Tests/TestStringView.cpp | 10 ++++++++++ 3 files changed, 22 insertions(+) diff --git a/AK/StringView.cpp b/AK/StringView.cpp index 12f39049e1e..54c1e21dcc4 100644 --- a/AK/StringView.cpp +++ b/AK/StringView.cpp @@ -92,6 +92,17 @@ bool StringView::starts_with(const StringView& str) const return !memcmp(characters_without_null_termination(), str.characters_without_null_termination(), str.length()); } +bool StringView::ends_with(const StringView& str) const +{ + if (str.is_empty()) + return true; + if (is_empty()) + return false; + if (str.length() > length()) + return false; + return !memcmp(characters_without_null_termination() + length() - str.length(), str.characters_without_null_termination(), str.length()); +} + StringView StringView::substring_view(size_t start, size_t length) const { if (!length) diff --git a/AK/StringView.h b/AK/StringView.h index e8cdbbbd450..d26d64c4d56 100644 --- a/AK/StringView.h +++ b/AK/StringView.h @@ -42,6 +42,7 @@ public: unsigned hash() const; bool starts_with(const StringView&) const; + bool ends_with(const StringView&) const; StringView substring_view(size_t start, size_t length) const; Vector split_view(char, bool keep_empty = false) const; diff --git a/AK/Tests/TestStringView.cpp b/AK/Tests/TestStringView.cpp index efe25961514..e1af2efa467 100644 --- a/AK/Tests/TestStringView.cpp +++ b/AK/Tests/TestStringView.cpp @@ -42,6 +42,16 @@ TEST_CASE(starts_with) EXPECT(!test_string_view.starts_with("DEF")); } +TEST_CASE(ends_with) +{ + String test_string = "ABCDEF"; + StringView test_string_view = test_string.view(); + EXPECT(test_string_view.ends_with("DEF")); + EXPECT(test_string_view.ends_with("ABCDEF")); + EXPECT(!test_string_view.ends_with("ABCDE")); + EXPECT(!test_string_view.ends_with("ABCDEFG")); +} + TEST_CASE(lines) { String test_string = "a\nb\r\nc\rd";