diff --git a/format.h b/format.h index 2f714001..3d756760 100644 --- a/format.h +++ b/format.h @@ -287,15 +287,30 @@ class BasicStringRef { /** Returns the string size. */ std::size_t size() const { return size_; } + // Lexicographically compare this string reference to other. + int compare(BasicStringRef other) const { + std::size_t size = std::min(size_, other.size_); + int result = std::char_traits::compare(data_, other.data_, size); + return result != 0 ? result : size_ - other.size_; + } + friend bool operator==(BasicStringRef lhs, BasicStringRef rhs) { - return lhs.data_ == rhs.data_; + return lhs.compare(rhs) == 0; } friend bool operator!=(BasicStringRef lhs, BasicStringRef rhs) { - return lhs.data_ != rhs.data_; + return lhs.compare(rhs) != 0; } friend bool operator<(BasicStringRef lhs, BasicStringRef rhs) { - return std::lexicographical_compare( - lhs.data_, lhs.data_ + lhs.size_, rhs.data_, rhs.data_ + rhs.size_); + return lhs.compare(rhs) < 0; + } + friend bool operator<=(BasicStringRef lhs, BasicStringRef rhs) { + return lhs.compare(rhs) <= 0; + } + friend bool operator>(BasicStringRef lhs, BasicStringRef rhs) { + return lhs.compare(rhs) > 0; + } + friend bool operator>=(BasicStringRef lhs, BasicStringRef rhs) { + return lhs.compare(rhs) >= 0; } }; diff --git a/test/util-test.cc b/test/util-test.cc index b92171ab..6da9553a 100644 --- a/test/util-test.cc +++ b/test/util-test.cc @@ -705,6 +705,33 @@ TEST(UtilTest, StringRef) { EXPECT_LT(std::strlen(str), sizeof(str)); } +// Check StringRef's comparison operator. +template