Browse Source

[2238] IOAddress comparison operator.

Tomek Mrugalski 12 years ago
parent
commit
c16a30cbaf
2 changed files with 61 additions and 2 deletions
  1. 35 2
      src/lib/asiolink/io_address.h
  2. 26 0
      src/lib/asiolink/tests/io_address_unittest.cc

+ 35 - 2
src/lib/asiolink/io_address.h

@@ -131,7 +131,7 @@ public:
         return equals(other);
     }
 
-    // \brief Compare addresses for inequality
+    /// \brief Compare addresses for inequality
     ///
     /// \param other Address to compare against.
     ///
@@ -140,7 +140,40 @@ public:
         return (!equals(other));
     }
 
-    // \brief Compare addresses for inequality
+    /// \brief Checks if one address is smaller than the other
+    ///
+    /// \param other Address to compare against.
+    ///
+    /// \return true if this address is smaller than the other address.
+    ///
+    /// It is useful for comparing which address is bigger.
+    /// Operations within one protocol family are obvious.
+    /// Comparisons between v4 and v6 will allways return v4
+    /// being smaller. This follows boost::asio::ip implementation
+    bool smaller_than(const IOAddress& other) const {
+        if (this->getFamily() < other.getFamily()) {
+            return (true);
+        }
+        if (this->getFamily() > other.getFamily()) {
+            return (false);
+        }
+        if (this->getFamily() == AF_INET6) {
+            return (this->asio_address_.to_v6() < other.asio_address_.to_v6());
+        } else {
+            return (this->asio_address_.to_v4() < other.asio_address_.to_v4());
+        }
+    }
+
+    /// \brief Checks if one address is smaller than the other
+    ///
+    /// \param other Address to compare against.
+    ///
+    /// See \ref smaller_than method for details.
+    bool operator<(const IOAddress& other) const {
+        return (smaller_than(other));
+    }
+
+    /// \brief Compare addresses for inequality
     ///
     /// \param other Address to compare against.
     ///

+ 26 - 0
src/lib/asiolink/tests/io_address_unittest.cc

@@ -99,3 +99,29 @@ TEST(IOAddressTest, uint32) {
 
     EXPECT_EQ(addr3.toText(), "192.0.2.5");
 }
+
+TEST(IOAddressTest, compare) {
+    IOAddress addr1("192.0.2.5");
+    IOAddress addr2("192.0.2.6");
+    IOAddress addr3("0.0.0.0");
+
+    IOAddress addr4("::");
+    IOAddress addr5("2001:db8::1");
+    IOAddress addr6("2001:db8::1:0");
+
+    // v4 comparisons
+    EXPECT_TRUE(addr1 < addr2);
+    EXPECT_FALSE(addr2 < addr1);
+    EXPECT_TRUE(addr3 < addr1);
+    EXPECT_TRUE(addr3 < addr2);
+
+    // v6 comparisons
+    EXPECT_TRUE(addr4 < addr5);
+    EXPECT_TRUE(addr5 < addr6);
+    EXPECT_FALSE(addr6 < addr5);
+
+    // v4 to v6 - v4 should always be smaller
+    EXPECT_TRUE(addr1 < addr4);
+    EXPECT_TRUE(addr3 < addr4);
+    EXPECT_TRUE(addr2 < addr5);
+}