From ec5101a1d3cc7bc9068fa4863e16aa482536929a Mon Sep 17 00:00:00 2001 From: Sam Atkins Date: Fri, 15 Nov 2024 13:08:15 +0000 Subject: [PATCH] AK: Ensure empty StringViews all compare as equal Before this change, a StringView with a character-data pointer would never compare as equal to one with a null pointer, even if they were both length 0. This could happen for example if one is default-initialized, and the other is created as a substring. --- AK/StringView.h | 3 +++ Tests/AK/TestStringView.cpp | 7 +++++++ 2 files changed, 10 insertions(+) diff --git a/AK/StringView.h b/AK/StringView.h index e73daa808b5..fa81b94f824 100644 --- a/AK/StringView.h +++ b/AK/StringView.h @@ -283,6 +283,9 @@ public: [[nodiscard]] constexpr int compare(StringView other) const { + if (m_length == 0 && other.m_length == 0) + return 0; + if (m_characters == nullptr) return other.m_characters ? -1 : 0; diff --git a/Tests/AK/TestStringView.cpp b/Tests/AK/TestStringView.cpp index a4199b22a36..f9744ab7ed4 100644 --- a/Tests/AK/TestStringView.cpp +++ b/Tests/AK/TestStringView.cpp @@ -38,6 +38,13 @@ TEST_CASE(compare_views) EXPECT_EQ(view1, foo1); EXPECT_EQ(view1, foo2); EXPECT_EQ(view1, "foo"); + + ByteString empty = ""; + auto empty_view = view1.substring_view(0, 0); + StringView default_view = {}; + EXPECT_EQ(empty.view(), ""sv); + EXPECT_EQ(empty_view, ""sv); + EXPECT_EQ(default_view, ""sv); } TEST_CASE(conforms_to_iterator_protocol)