From 6a51093ab14444b9b513ef42fbc51b85dd346f55 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Sat, 8 Jun 2019 18:30:40 +0200 Subject: [PATCH] AK: Add String::operator==(const char*). Without this function, comparing a String to a const char* will instantiate a temporary String which is obviously not great. Also add some missing null checks to StringView::operator==(const char*). --- AK/AKString.h | 14 ++++++++++++++ AK/StringView.h | 5 +++++ 2 files changed, 19 insertions(+) diff --git a/AK/AKString.h b/AK/AKString.h index 612dae31cc1..86108dae164 100644 --- a/AK/AKString.h +++ b/AK/AKString.h @@ -133,6 +133,20 @@ public: bool operator!=(const String& other) const { return !(*this == other); } bool operator<(const String&) const; + bool operator==(const char* cstring) const + { + if (is_null()) + return !cstring; + if (!cstring) + return false; + return !strcmp(characters(), cstring); + } + + bool operator!=(const char* cstring) const + { + return !(*this == cstring); + } + String isolated_copy() const; static String empty(); diff --git a/AK/StringView.h b/AK/StringView.h index c5a0b1a7a15..495c2055fe6 100644 --- a/AK/StringView.h +++ b/AK/StringView.h @@ -29,6 +29,7 @@ public: } StringView(const AK::String& string); + bool is_null() const { return !m_characters; } bool is_empty() const { return m_length == 0; } const char* characters() const { return m_characters; } int length() const { return m_length; } @@ -40,6 +41,10 @@ public: bool operator==(const char* cstring) const { + if (is_null()) + return !cstring; + if (!cstring) + return false; int other_length = strlen(cstring); if (m_length != other_length) return false;