Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/catch2/internal/catch_stringref.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,16 @@ namespace Catch {

bool StringRef::operator<(StringRef rhs) const noexcept {
if (m_size < rhs.m_size) {
return strncmp(m_start, rhs.m_start, m_size) <= 0;
return std::memcmp(m_start, rhs.m_start, m_size) <= 0;
}
return strncmp(m_start, rhs.m_start, rhs.m_size) < 0;
return std::memcmp(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 ) );
std::memcmp( m_start, rhs.m_start, std::min( m_size, rhs.m_size ) );

// This means that strncmp found a difference before the strings
// This means that memcmp found a difference before the strings
// ended, and we can return it directly
if ( cmpResult != 0 ) {
return cmpResult;
Expand Down
45 changes: 45 additions & 0 deletions tests/SelfTest/IntrospectiveTests/String.tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include <catch2/internal/catch_stringref.hpp>

#include <cstring>
#include <set>

TEST_CASE( "StringRef", "[Strings][StringRef]" ) {
using Catch::StringRef;
Expand Down Expand Up @@ -204,3 +205,47 @@ TEST_CASE("StringRef::compare", "[Strings][StringRef][approvals]") {
REQUIRE(sr3.compare(sr2) < 0);
}
}

TEST_CASE( "StringRef comparisons include embedded nulls",
"[Strings][StringRef][approvals]" ) {
using Catch::StringRef;
using Catch::operator""_sr;

SECTION( "Equal lengths with different characters after the null" ) {
const auto lhs = "a\0b"_sr;
const auto rhs = "a\0c"_sr;

CHECK( lhs != rhs );
CHECK( lhs < rhs );
CHECK_FALSE( rhs < lhs );
CHECK( lhs.compare( rhs ) < 0 );
CHECK( rhs.compare( lhs ) > 0 );
}

SECTION( "Characters after the null take precedence over length" ) {
const auto shorter = "a\0z"_sr;
const auto longer = "a\0aa"_sr;

CHECK_FALSE( shorter < longer );
CHECK( longer < shorter );
CHECK( shorter.compare( longer ) > 0 );
CHECK( longer.compare( shorter ) < 0 );
}

SECTION( "Matching prefixes are ordered by length" ) {
const auto prefix = "a\0b"_sr;
const auto longer = "a\0b\0"_sr;

CHECK( prefix < longer );
CHECK_FALSE( longer < prefix );
CHECK( prefix.compare( longer ) < 0 );
CHECK( longer.compare( prefix ) > 0 );
CHECK( prefix.compare( prefix ) == 0 );
}

SECTION( "Ordered containers keep distinct strings" ) {
const std::set<StringRef> strings{ "a\0b"_sr, "a\0c"_sr };

CHECK( strings.size() == 2 );
}
}