fix: revert "perf: improve IPv4 `tr_address` comparison" (#5709)

* Revert "perf: improve IPv4 `tr_address` comparison (#5651)"

This reverts commit 70decc1d9d.

* added tests

* add ipv4 equal test and std header
This commit is contained in:
tearfur 2023-07-01 22:39:35 +08:00 committed by GitHub
parent 0fbafc9e18
commit 9c17463a80
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 3 deletions

View File

@ -596,9 +596,7 @@ int tr_address::compare(tr_address const& that) const noexcept // <=>
return this->is_ipv4() ? 1 : -1;
}
// in_addr_t is by definition uint32_t, so we convert it to int64_t,
// the smallest signed integer type that can contain all values of uint32_t.
return this->is_ipv4() ? static_cast<int>(int64_t{ ntohl(this->addr.addr4.s_addr) } - ntohl(that.addr.addr4.s_addr)) :
return this->is_ipv4() ? memcmp(&this->addr.addr4, &that.addr.addr4, sizeof(this->addr.addr4)) :
memcmp(&this->addr.addr6.s6_addr, &that.addr.addr6.s6_addr, sizeof(this->addr.addr6.s6_addr));
}

View File

@ -5,6 +5,7 @@
#include <array>
#include <string_view>
#include <tuple>
#include <utility>
#include <libtransmission/transmission.h>
@ -179,3 +180,28 @@ TEST_F(NetTest, isGlobalUnicastAddress)
EXPECT_EQ(expected, address->is_global_unicast_address()) << presentation;
}
}
TEST_F(NetTest, ipCompare)
{
static auto constexpr IpPairs = std::array{ std::tuple{ "223.18.245.229"sv, "8.8.8.8"sv, 1 },
std::tuple{ "0.0.0.0"sv, "255.255.255.255"sv, -1 },
std::tuple{ "8.8.8.8"sv, "8.8.8.8"sv, 0 },
std::tuple{ "8.8.8.8"sv, "2001:0:0eab:dead::a0:abcd:4e"sv, 1 },
std::tuple{ "2001:1890:1112:1::20"sv, "2001:0:0eab:dead::a0:abcd:4e"sv, 1 },
std::tuple{ "2001:1890:1112:1::20"sv, "2001:1890:1112:1::20"sv, 0 } };
for (auto const& [ip_str1, ip_str2, res] : IpPairs)
{
auto const ip1 = *tr_address::from_string(ip_str1);
auto const ip2 = *tr_address::from_string(ip_str2);
std::cerr << ip_str1 << " Vs " << ip_str2 << std::endl;
EXPECT_EQ(ip1.compare(ip2) < 0, res < 0);
EXPECT_EQ(ip1.compare(ip2) > 0, res > 0);
EXPECT_EQ(ip1.compare(ip2) == 0, res == 0);
EXPECT_EQ(ip1 < ip2, res < 0);
EXPECT_EQ(ip1 > ip2, res > 0);
EXPECT_EQ(ip1 == ip2, res == 0);
}
}