From ca58c71faa6e31721b6094d380732d2aa6f3d791 Mon Sep 17 00:00:00 2001 From: Daniel Bertalan Date: Sat, 29 Jan 2022 15:49:33 +0100 Subject: [PATCH] AK: Implement all comparison operators for StringView --- AK/StringView.cpp | 10 +--------- AK/StringView.h | 37 +++++++++++++++++++++++-------------- 2 files changed, 24 insertions(+), 23 deletions(-) diff --git a/AK/StringView.cpp b/AK/StringView.cpp index 4a569bbcb8..3879d45295 100644 --- a/AK/StringView.cpp +++ b/AK/StringView.cpp @@ -203,15 +203,7 @@ template Optional StringView::to_uint() const; bool StringView::operator==(const String& string) const { - if (string.is_null()) - return !m_characters; - if (!m_characters) - return false; - if (m_length != string.length()) - return false; - if (m_characters == string.characters()) - return true; - return !__builtin_memcmp(m_characters, string.characters(), m_length); + return *this == string.view(); } String StringView::to_string() const { return String { *this }; } diff --git a/AK/StringView.h b/AK/StringView.h index a63f0590b5..e6a5b492be 100644 --- a/AK/StringView.h +++ b/AK/StringView.h @@ -204,28 +204,37 @@ public: bool operator==(const String&) const; + [[nodiscard]] constexpr int compare(StringView other) const + { + size_t rlen = min(length(), other.length()); + int c = (rlen != 0) ? __builtin_memcmp(m_characters, other.m_characters, rlen) : 0; + if (c == 0) { + if (length() < other.length()) + return -1; + if (length() == other.length()) + return 0; + return 1; + } + return c; + } + constexpr bool operator==(StringView other) const { - if (is_null()) - return other.is_null(); - if (other.is_null()) - return false; - if (length() != other.length()) - return false; - return __builtin_memcmp(m_characters, other.m_characters, m_length) == 0; + return length() == other.length() && compare(other) == 0; } constexpr bool operator!=(StringView other) const { - return !(*this == other); + return length() != other.length() || compare(other) != 0; } - bool operator<(StringView other) const - { - if (int c = __builtin_memcmp(m_characters, other.m_characters, min(m_length, other.m_length))) - return c < 0; - return m_length < other.m_length; - } + constexpr bool operator<(StringView other) const { return compare(other) < 0; } + + constexpr bool operator<=(StringView other) const { return compare(other) <= 0; } + + constexpr bool operator>(StringView other) const { return compare(other) > 0; } + + constexpr bool operator>=(StringView other) const { return compare(other) >= 0; } [[nodiscard]] String to_string() const;