Add new toBinary() function to IPAddress.
authorFlorent Thoumie <ft@fb.com>
Mon, 26 Oct 2015 21:53:03 +0000 (14:53 -0700)
committerfacebook-github-bot-1 <folly-bot@fb.com>
Mon, 26 Oct 2015 22:20:20 +0000 (15:20 -0700)
Summary: This is pretty much the reverse operation from the fromBinary() constructor.

Reviewed By: yfeldblum

Differential Revision: D2578680

fb-gh-sync-id: d8c4e53fe8bc0f5373ebb0b4f7ee498659c1b003

folly/IPAddressV4.h
folly/IPAddressV6.h
folly/test/IPAddressTest.cpp

index bc7be1cf842a3e40ec1f892b3d01f06ee6ebd093..1feac577148e01d140ded5c831cc58f2f97ecc0a 100644 (file)
@@ -68,6 +68,13 @@ class IPAddressV4 : boost::totally_ordered<IPAddressV4> {
     return addr;
   }
 
+  /**
+   * Returns the address as a Range.
+   */
+  ByteRange toBinary() const {
+    return ByteRange((const unsigned char *) &addr_.inAddr_.s_addr, 4);
+  }
+
   /**
    * Convert a IPv4 address string to a long in network byte order.
    * @param [in] ip the address to convert
index d4876af6c6fb70c37c942d35dec31b5ac5a4315b..22ff36514213f6b5e6e57f22c8510f947da4bed0 100644 (file)
@@ -96,6 +96,13 @@ class IPAddressV6 : boost::totally_ordered<IPAddressV6> {
     return addr;
   }
 
+  /**
+   * Returns the address as a Range.
+   */
+  ByteRange toBinary() const {
+    return ByteRange((const unsigned char *) &addr_.in6Addr_.s6_addr, 16);
+  }
+
   /**
    * Default constructor for IPAddressV6.
    *
index f603fe122e6d151f828699ca6b1508b2509ddb51..679c76233a66d9376b3d9c045e709f634e0d3a1d 100644 (file)
@@ -631,6 +631,22 @@ TEST(IPAddress, fromBinaryV4) {
                IPAddressFormatException);
 }
 
+TEST(IPAddress, toBinaryV4) {
+  for (auto& tc : provideToLong) {
+    SCOPED_TRACE(tc.first);
+    union {
+      uint8_t u8[4];
+      uint32_t u32;
+    } data;
+    data.u32 = Endian::big(tc.second);
+    ByteRange bytes(data.u8, 4);
+
+    auto fromBin = IPAddressV4::fromBinary(bytes);
+    auto toBin = fromBin.toBinary();
+    EXPECT_EQ(bytes, toBin);
+  }
+}
+
 static const vector<pair<string, vector<uint8_t> > > provideBinary16Bytes = {
   {"::0",
     {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
@@ -677,6 +693,17 @@ TEST(IPAddress, fromBinaryV6) {
                IPAddressFormatException);
 }
 
+TEST(IPAddress, toBinaryV6) {
+  for (auto& tc : provideBinary16Bytes) {
+    SCOPED_TRACE(tc.first);
+    ByteRange bytes(&tc.second.front(), tc.second.size());
+
+    auto fromBin = IPAddressV6::fromBinary(bytes);
+    auto toBin = fromBin.toBinary();
+    EXPECT_EQ(bytes, toBin);
+  }
+}
+
 TEST_P(IPAddressFlagTest, IsLoopback) {
   AddressFlags param = GetParam();
   IPAddress addr(param.address);