mirror of
https://github.com/catchorg/Catch2.git
synced 2025-08-04 14:25:40 +02:00
Add StringRef::compare for three way comparison
This commit is contained in:
@@ -29,6 +29,27 @@ namespace Catch {
|
||||
return strncmp(m_start, rhs.m_start, rhs.m_size) < 0;
|
||||
}
|
||||
|
||||
int StringRef::compare( StringRef rhs ) const {
|
||||
auto cmpResult =
|
||||
strncmp( m_start, rhs.m_start, std::min( m_size, rhs.m_size ) );
|
||||
|
||||
// This means that strncmp found a difference before the strings
|
||||
// ended, and we can return it directly
|
||||
if ( cmpResult != 0 ) {
|
||||
return cmpResult;
|
||||
}
|
||||
|
||||
// If strings are equal up to length, then their comparison results on
|
||||
// their size
|
||||
if ( m_size < rhs.m_size ) {
|
||||
return -1;
|
||||
} else if ( m_size > rhs.m_size ) {
|
||||
return 1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
|
||||
return os.write(str.data(), str.size());
|
||||
}
|
||||
|
@@ -69,7 +69,6 @@ namespace Catch {
|
||||
return m_size;
|
||||
}
|
||||
|
||||
public: // substrings and searches
|
||||
// Returns a substring of [start, start + length).
|
||||
// If start + length > size(), then the substring is [start, start + size()).
|
||||
// If start > size(), then the substring is empty.
|
||||
@@ -87,7 +86,6 @@ namespace Catch {
|
||||
return m_start;
|
||||
}
|
||||
|
||||
public: // iterators
|
||||
constexpr const_iterator begin() const { return m_start; }
|
||||
constexpr const_iterator end() const { return m_start + m_size; }
|
||||
|
||||
@@ -95,6 +93,14 @@ namespace Catch {
|
||||
friend std::string& operator += (std::string& lhs, StringRef const& sr);
|
||||
friend std::ostream& operator << (std::ostream& os, StringRef const& sr);
|
||||
friend std::string operator+(StringRef lhs, StringRef rhs);
|
||||
|
||||
/**
|
||||
* Provides a three-way comparison with rhs
|
||||
*
|
||||
* Returns negative number if lhs < rhs, 0 if lhs == rhs, and a positive
|
||||
* number if lhs > rhs
|
||||
*/
|
||||
int compare( StringRef rhs ) const;
|
||||
};
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user