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.
This commit is contained in:
Sam Atkins 2024-11-15 13:08:15 +00:00 committed by Andreas Kling
parent 87fc7028d7
commit ec5101a1d3
Notes: github-actions[bot] 2024-11-15 22:27:14 +00:00
2 changed files with 10 additions and 0 deletions

View file

@ -283,6 +283,9 @@ public:
[[nodiscard]] constexpr int compare(StringView other) const [[nodiscard]] constexpr int compare(StringView other) const
{ {
if (m_length == 0 && other.m_length == 0)
return 0;
if (m_characters == nullptr) if (m_characters == nullptr)
return other.m_characters ? -1 : 0; return other.m_characters ? -1 : 0;

View file

@ -38,6 +38,13 @@ TEST_CASE(compare_views)
EXPECT_EQ(view1, foo1); EXPECT_EQ(view1, foo1);
EXPECT_EQ(view1, foo2); EXPECT_EQ(view1, foo2);
EXPECT_EQ(view1, "foo"); 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) TEST_CASE(conforms_to_iterator_protocol)