From 202e9feed09f7cb7d41c004d414283b262a95204 Mon Sep 17 00:00:00 2001 From: crupest Date: Fri, 13 Aug 2021 15:24:39 +0800 Subject: ... --- include/cru/common/Base.hpp | 25 +++++++++++++++++++++++++ include/cru/common/String.hpp | 5 +++++ src/common/String.cpp | 31 +++++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+) diff --git a/include/cru/common/Base.hpp b/include/cru/common/Base.hpp index 5ed1e763..2f76385e 100644 --- a/include/cru/common/Base.hpp +++ b/include/cru/common/Base.hpp @@ -42,6 +42,31 @@ classname() = default; \ ~classname() override = default; +#define CRU_DEFINE_COMPARE_OPERATORS(classname) \ + inline bool operator==(const classname& left, const classname& right) { \ + return left.Compare(right) == 0; \ + } \ + \ + inline bool operator!=(const classname& left, const classname& right) { \ + return left.Compare(right) != 0; \ + } \ + \ + inline bool operator<(const classname& left, const classname& right) { \ + return left.Compare(right) < 0; \ + } \ + \ + inline bool operator<=(const classname& left, const classname& right) { \ + return left.Compare(right) <= 0; \ + } \ + \ + inline bool operator>(const classname& left, const classname& right) { \ + return left.Compare(right) > 0; \ + } \ + \ + inline bool operator>=(const classname& left, const classname& right) { \ + return left.Compare(right) >= 0; \ + } + namespace cru { class CRU_BASE_API Object { public: diff --git a/include/cru/common/String.hpp b/include/cru/common/String.hpp index e779e3a6..c8defd13 100644 --- a/include/cru/common/String.hpp +++ b/include/cru/common/String.hpp @@ -139,6 +139,8 @@ class CRU_BASE_API String { std::string ToUtf8() const; + int Compare(const String& other) const; + private: static std::uint16_t kEmptyBuffer[1]; @@ -147,4 +149,7 @@ class CRU_BASE_API String { Index size_ = 0; // not including trailing '\0' Index capacity_ = 0; // always 1 smaller than real buffer size }; + +CRU_DEFINE_COMPARE_OPERATORS(String) + } // namespace cru diff --git a/src/common/String.cpp b/src/common/String.cpp index 91422d48..83dd8aa8 100644 --- a/src/common/String.cpp +++ b/src/common/String.cpp @@ -148,4 +148,35 @@ std::string String::ToUtf8() const { return cru::ToUtf8(std::u16string_view(Char16CStr(), size())); } +namespace { +inline int Compare(std::uint16_t left, std::uint16_t right) { + if (left < right) return -1; + if (left > right) return 1; + return 0; +} +} // namespace + +int String::Compare(const String& other) const { + const_iterator i1 = cbegin(); + const_iterator i2 = other.cbegin(); + + const_iterator end1 = cend(); + const_iterator end2 = other.cend(); + + while (i1 != end1 && i2 != end2) { + int r = cru::Compare(*i1, *i2); + if (r != 0) return r; + } + + if (i1 == end1) { + if (i2 == end1) { + return 0; + } else { + return -1; + } + } else { + return 1; + } +} + } // namespace cru -- cgit v1.2.3