Skip to content

Commit

Permalink
implement threeway comparison (#40)
Browse files Browse the repository at this point in the history
  • Loading branch information
timblechmann committed Oct 4, 2023
1 parent 492ba1b commit 92df4b2
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
16 changes: 16 additions & 0 deletions include/semver.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,11 @@
# pragma clang diagnostic ignored "-Wmissing-braces" // Ignore warning: suggest braces around initialization of subobject 'return {first, std::errc::invalid_argument};'.
#endif

#if __cpp_impl_three_way_comparison >= 201907L
#include <compare>
#endif


namespace semver {

enum struct prerelease : std::uint8_t {
Expand Down Expand Up @@ -482,6 +487,17 @@ struct version {
return lhs.compare(rhs) <= 0;
}

#if __cpp_impl_three_way_comparison >= 201907L
[[nodiscard]] constexpr std::strong_ordering operator<=>(const version& lhs, const version& rhs) {
int compare = lhs.compare(rhs);
if ( compare == 0 )
return std::strong_ordering::equal;
if ( compare > 0 )
return std::strong_ordering::greater;
return std::strong_ordering::less;
}
#endif

[[nodiscard]] constexpr version operator""_version(const char* str, std::size_t length) {
return version{std::string_view{str, length}};
}
Expand Down
27 changes: 27 additions & 0 deletions test/test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,33 @@ TEST_CASE("operators") {
}
}

#if __cpp_impl_three_way_comparison >= 201907L
SECTION("operator <=>") {
constexpr version v1{1, 2, 3, prerelease::rc, 4};
constexpr version v2{1, 2, 3};
constexpr version v3{1, 2, 3};
REQUIRE(v1 <=> v1 == std::strong_ordering::equal);
REQUIRE(v2 <=> v3 == std::strong_ordering::equal);

auto validate_threeway_compare = [] (auto v1, auto v2) {
if (v1 < v2)
REQUIRE(v1 <=> v2 == std::strong_ordering::less);
else if (v1 > v2)
REQUIRE(v1 <=> v2 == std::strong_ordering::greater);
else if (v1 == v2)
REQUIRE(v1 <=> v2 == std::strong_ordering::equal);
};

for (std::size_t i = 1; i < versions.size(); ++i) {
for (std::size_t j = 1; j < i; ++j) {
version v = versions[i - j];
validate_threeway_compare(versions[i - j], versions[i]);
validate_threeway_compare(v, versions[i - j]);
}
}
}
#endif

SECTION("operator _version") {
constexpr version v = "1.2.3-rc.4"_version;
static_assert(v == version{1, 2, 3, prerelease::rc, 4});
Expand Down

0 comments on commit 92df4b2

Please sign in to comment.