Consistent use of sformat in address-related files v2017.08.07.00
authorYedidya Feldblum <yfeldblum@fb.com>
Sun, 6 Aug 2017 05:09:13 +0000 (22:09 -0700)
committerFacebook Github Bot <facebook-github-bot@users.noreply.github.com>
Sun, 6 Aug 2017 05:11:51 +0000 (22:11 -0700)
Summary:
[Folly] Consistent use of `sformat` in address-related files.

V.s. `format(/*...*/).str()` and v.s. `to<std::string>`.

Reviewed By: meyering

Differential Revision: D5570334

fbshipit-source-id: 83aedf9a694721fb209e62e94f1a5c5ecd355e81

folly/IPAddress.cpp
folly/IPAddressV4.cpp
folly/IPAddressV6.cpp
folly/MacAddress.cpp
folly/SocketAddress.cpp
folly/detail/IPAddress.cpp
folly/detail/IPAddressSource.h
folly/test/IPAddressBenchmark.cpp
folly/test/IPAddressTest.cpp
folly/test/MacAddressTest.cpp

index 75c2ff3d50e6cd7563abdca611ff583da4a53114..505e769d951bf8d208d35c74a6e75c18525e5667 100644 (file)
@@ -21,7 +21,7 @@
 #include <string>
 #include <vector>
 
-#include <folly/Conv.h>
+#include <folly/Format.h>
 #include <folly/String.h>
 #include <folly/detail/IPAddressSource.h>
 
@@ -81,12 +81,9 @@ CIDRNetwork IPAddress::createNetwork(StringPiece ipSlashCidr,
 
   if (elemCount == 0 || // weird invalid string
       elemCount > 2) { // invalid string (IP/CIDR/extras)
-    throw IPAddressFormatException(to<std::string>(
-        "Invalid ipSlashCidr specified. ",
-        "Expected IP/CIDR format, got ",
-        "'",
-        ipSlashCidr,
-        "'"));
+    throw IPAddressFormatException(sformat(
+        "Invalid ipSlashCidr specified. Expected IP/CIDR format, got '{}'",
+        ipSlashCidr));
   }
   IPAddress subnet(vec.at(0));
   auto cidr =
@@ -97,25 +94,21 @@ CIDRNetwork IPAddress::createNetwork(StringPiece ipSlashCidr,
       cidr = to<uint8_t>(vec.at(1));
     } catch (...) {
       throw IPAddressFormatException(
-          to<std::string>("Mask value ", "'", vec.at(1), "' not a valid mask"));
+          sformat("Mask value '{}' not a valid mask", vec.at(1)));
     }
   }
   if (cidr > subnet.bitCount()) {
-    throw IPAddressFormatException(to<std::string>(
-        "CIDR value '",
+    throw IPAddressFormatException(sformat(
+        "CIDR value '{}' is > network bit count '{}'",
         cidr,
-        "' ",
-        "is > network bit count ",
-        "'",
-        subnet.bitCount(),
-        "'"));
+        subnet.bitCount()));
   }
   return std::make_pair(applyMask ? subnet.mask(cidr) : subnet, cidr);
 }
 
 // public static
 std::string IPAddress::networkToString(const CIDRNetwork& network) {
-  return network.first.str() + "/" + folly::to<std::string>(network.second);
+  return sformat("{}/{}", network.first.str(), network.second);
 }
 
 // public static
@@ -127,7 +120,7 @@ IPAddress IPAddress::fromBinary(ByteRange bytes) {
   } else {
     string hexval = detail::Bytes::toHex(bytes.data(), bytes.size());
     throw IPAddressFormatException(
-        to<std::string>("Invalid address with hex value ", "'", hexval, "'"));
+        sformat("Invalid address with hex value '{}'", hexval));
   }
 }
 
@@ -153,8 +146,7 @@ IPAddress::IPAddress(StringPiece addr)
 {
   string ip = addr.str();  // inet_pton() needs NUL-terminated string
   auto throwFormatException = [&](const string& msg) {
-    throw IPAddressFormatException(
-        to<std::string>("Invalid IP '", ip, "': ", msg));
+    throw IPAddressFormatException(sformat("Invalid IP '{}': {}", ip, msg));
   };
 
   if (ip.size() < 2) {
@@ -333,8 +325,9 @@ bool IPAddress::inSubnetWithMask(const IPAddress& subnet,
 uint8_t IPAddress::getNthMSByte(size_t byteIndex) const {
   const auto highestIndex = byteCount() - 1;
   if (byteIndex > highestIndex) {
-    throw std::invalid_argument(to<string>("Byte index must be <= ",
-        to<string>(highestIndex), " for addresses of type :",
+    throw std::invalid_argument(sformat(
+        "Byte index must be <= {} for addresses of type: {}",
+        highestIndex,
         detail::familyNameStr(family())));
   }
   if (isV4()) {
@@ -402,10 +395,11 @@ bool operator<(const IPAddress& addr1, const IPAddress& addr2) {
 CIDRNetwork
 IPAddress::longestCommonPrefix(const CIDRNetwork& one, const CIDRNetwork& two) {
   if (one.first.family() != two.first.family()) {
-      throw std::invalid_argument(to<string>("Can't compute "
-            "longest common prefix between addresses of different families. "
-            "Passed: ", detail::familyNameStr(one.first.family()), " and ",
-            detail::familyNameStr(two.first.family())));
+    throw std::invalid_argument(sformat(
+        "Can't compute longest common prefix between addresses of different"
+        "families. Passed: {} and {}",
+        detail::familyNameStr(one.first.family()),
+        detail::familyNameStr(two.first.family())));
   }
   if (one.first.isV4()) {
     auto prefix = IPAddressV4::longestCommonPrefix(
@@ -424,14 +418,14 @@ IPAddress::longestCommonPrefix(const CIDRNetwork& one, const CIDRNetwork& two) {
 
 [[noreturn]] void IPAddress::asV4Throw() const {
   auto fam = detail::familyNameStr(family());
-  throw InvalidAddressFamilyException(to<std::string>(
-      "Can't convert address with family ", fam, " to AF_INET address"));
+  throw InvalidAddressFamilyException(
+      sformat("Can't convert address with family {} to AF_INET address", fam));
 }
 
 [[noreturn]] void IPAddress::asV6Throw() const {
   auto fam = detail::familyNameStr(family());
-  throw InvalidAddressFamilyException(to<std::string>(
-      "Can't convert address with family ", fam, " to AF_INET6 address"));
+  throw InvalidAddressFamilyException(
+      sformat("Can't convert address with family {} to AF_INET6 address", fam));
 }
 
 } // namespace folly
index 645d5d2933b9ffe9ac8e5fa729eeca909a79a356..3e7704e01414f7d93f5d3752caa382aa8c2dc2b6 100644 (file)
@@ -74,7 +74,7 @@ uint32_t IPAddressV4::toLong(StringPiece ip) {
   in_addr addr;
   if (inet_pton(AF_INET, str.c_str(), &addr) != 1) {
     throw IPAddressFormatException(
-        to<std::string>("Can't convert invalid IP '", ip, "' ", "to long"));
+        sformat("Can't convert invalid IP '{}' to long", ip));
   }
   return addr.s_addr;
 }
@@ -100,8 +100,7 @@ IPAddressV4::IPAddressV4(StringPiece addr)
 {
   auto ip = addr.str();
   if (inet_pton(AF_INET, ip.c_str(), &addr_.inAddr_) != 1) {
-    throw IPAddressFormatException(
-        to<std::string>("Invalid IPv4 address '", addr, "'"));
+    throw IPAddressFormatException(sformat("Invalid IPv4 address '{}'", addr));
   }
 }
 
@@ -114,9 +113,8 @@ IPAddressV4::IPAddressV4(const in_addr src)
 // public
 void IPAddressV4::setFromBinary(ByteRange bytes) {
   if (bytes.size() != 4) {
-    throw IPAddressFormatException(to<std::string>(
-        "Invalid IPv4 binary data: length must ",
-        "be 4 bytes, got ",
+    throw IPAddressFormatException(sformat(
+        "Invalid IPv4 binary data: length must be 4 bytes, got {}",
         bytes.size()));
   }
   memcpy(&addr_.inAddr_.s_addr, bytes.data(), sizeof(in_addr));
@@ -159,8 +157,7 @@ IPAddressV6 IPAddressV4::getIPv6For6To4() const {
 
 // public
 string IPAddressV4::toJson() const {
-  return format(
-      "{{family:'AF_INET', addr:'{}', hash:{}}}", str(), hash()).str();
+  return sformat("{{family:'AF_INET', addr:'{}', hash:{}}}", str(), hash());
 }
 
 // public
@@ -168,8 +165,8 @@ bool IPAddressV4::inSubnet(StringPiece cidrNetwork) const {
   auto subnetInfo = IPAddress::createNetwork(cidrNetwork);
   auto addr = subnetInfo.first;
   if (!addr.isV4()) {
-    throw IPAddressFormatException(to<std::string>(
-        "Address '", addr.toJson(), "' ", "is not a V4 address"));
+    throw IPAddressFormatException(
+        sformat("Address '{}' is not a V4 address", addr.toJson()));
   }
   return inSubnetWithMask(addr.asV4(), fetchMask(subnetInfo.second));
 }
@@ -229,7 +226,7 @@ IPAddressV4 IPAddressV4::mask(size_t numBits) const {
   static const auto bits = bitCount();
   if (numBits > bits) {
     throw IPAddressFormatException(
-        to<std::string>("numBits(", numBits, ") > bitsCount(", bits, ")"));
+        sformat("numBits({}) > bitsCount({})", numBits, bits));
   }
 
   ByteArray4 ba = detail::Bytes::mask(fetchMask(numBits), addr_.bytes_);
@@ -260,8 +257,9 @@ string IPAddressV4::toInverseArpaName() const {
 uint8_t IPAddressV4::getNthMSByte(size_t byteIndex) const {
   const auto highestIndex = byteCount() - 1;
   if (byteIndex > highestIndex) {
-    throw std::invalid_argument(to<string>("Byte index must be <= ",
-        to<string>(highestIndex), " for addresses of type :",
+    throw std::invalid_argument(sformat(
+        "Byte index must be <= {} for addresses of type: {}",
+        highestIndex,
         detail::familyNameStr(AF_INET)));
   }
   return bytes()[byteIndex];
@@ -270,8 +268,7 @@ uint8_t IPAddressV4::getNthMSByte(size_t byteIndex) const {
 const ByteArray4 IPAddressV4::fetchMask(size_t numBits) {
   static const size_t bits = bitCount();
   if (numBits > bits) {
-    throw IPAddressFormatException(
-        to<std::string>("IPv4 addresses are 32 bits"));
+    throw IPAddressFormatException("IPv4 addresses are 32 bits");
   }
   auto const val = Endian::big(uint32_t(~uint64_t(0) << (32 - numBits)));
   ByteArray4 arr;
index e40a08e5d17e317f43fb6a6056569da41b1511a1..e77ea540b8e298fa941c0ef4b5f932861d4024f6 100644 (file)
@@ -87,7 +87,7 @@ IPAddressV6::IPAddressV6(StringPiece addr) {
   // Allow addresses surrounded in brackets
   if (ip.size() < 2) {
     throw IPAddressFormatException(
-        to<std::string>("Invalid IPv6 address '", ip, "': address too short"));
+        sformat("Invalid IPv6 address '{}': address too short", ip));
   }
   if (ip.front() == '[' && ip.back() == ']') {
     ip = ip.substr(1, ip.size() - 2);
@@ -105,8 +105,7 @@ IPAddressV6::IPAddressV6(StringPiece addr) {
     scope_ = uint16_t(ipAddr->sin6_scope_id);
     freeaddrinfo(result);
   } else {
-    throw IPAddressFormatException(
-        to<std::string>("Invalid IPv6 address '", ip, "'"));
+    throw IPAddressFormatException(sformat("Invalid IPv6 address '{}'", ip));
   }
 }
 
@@ -177,9 +176,8 @@ Optional<MacAddress> IPAddressV6::getMacAddressFromLinkLocal() const {
 
 void IPAddressV6::setFromBinary(ByteRange bytes) {
   if (bytes.size() != 16) {
-    throw IPAddressFormatException(to<std::string>(
-        "Invalid IPv6 binary data: length must ",
-        "be 16 bytes, got ",
+    throw IPAddressFormatException(sformat(
+        "Invalid IPv6 binary data: length must be 16 bytes, got {}",
         bytes.size()));
   }
   memcpy(&addr_.in6Addr_.s6_addr, bytes.data(), sizeof(in6_addr));
@@ -243,8 +241,8 @@ static inline void unpackInto(const unsigned char* src,
 // public
 IPAddressV4 IPAddressV6::getIPv4For6To4() const {
   if (!is6To4()) {
-    throw IPAddressV6::TypeError(format(
-            "Invalid IP '{}': not a 6to4 address", str()).str());
+    throw IPAddressV6::TypeError(
+        sformat("Invalid IP '{}': not a 6to4 address", str()));
   }
   // convert 16x8 bytes into first 4x16 bytes
   uint16_t ints[4] = {0,0,0,0};
@@ -299,8 +297,7 @@ IPAddressV6::Type IPAddressV6::type() const {
 
 // public
 string IPAddressV6::toJson() const {
-  return format(
-      "{{family:'AF_INET6', addr:'{}', hash:{}}}", str(), hash()).str();
+  return sformat("{{family:'AF_INET6', addr:'{}', hash:{}}}", str(), hash());
 }
 
 // public
@@ -323,8 +320,8 @@ bool IPAddressV6::inSubnet(StringPiece cidrNetwork) const {
   auto subnetInfo = IPAddress::createNetwork(cidrNetwork);
   auto addr = subnetInfo.first;
   if (!addr.isV6()) {
-    throw IPAddressFormatException(to<std::string>(
-        "Address '", addr.toJson(), "' ", "is not a V6 address"));
+    throw IPAddressFormatException(
+        sformat("Address '{}' is not a V6 address", addr.toJson()));
   }
   return inSubnetWithMask(addr.asV6(), fetchMask(subnetInfo.second));
 }
@@ -408,7 +405,7 @@ IPAddressV6 IPAddressV6::mask(size_t numBits) const {
   static const auto bits = bitCount();
   if (numBits > bits) {
     throw IPAddressFormatException(
-        to<std::string>("numBits(", numBits, ") > bitCount(", bits, ")"));
+        sformat("numBits({}) > bitCount({})", numBits, bits));
   }
   ByteArray16 ba = detail::Bytes::mask(fetchMask(numBits), addr_.bytes_);
   return IPAddressV6(ba);
@@ -419,12 +416,9 @@ string IPAddressV6::str() const {
   char buffer[INET6_ADDRSTRLEN + IFNAMSIZ + 1];
 
   if (!inet_ntop(AF_INET6, toAddr().s6_addr, buffer, INET6_ADDRSTRLEN)) {
-    throw IPAddressFormatException(to<std::string>(
-        "Invalid address with hex ",
-        "'",
+    throw IPAddressFormatException(sformat(
+        "Invalid address with hex '{}' with error {}",
         detail::Bytes::toHex(bytes(), 16),
-        "'",
-        " with error ",
         strerror(errno)));
   }
 
@@ -472,8 +466,9 @@ string IPAddressV6::toInverseArpaName() const {
 uint8_t IPAddressV6::getNthMSByte(size_t byteIndex) const {
   const auto highestIndex = byteCount() - 1;
   if (byteIndex > highestIndex) {
-    throw std::invalid_argument(to<string>("Byte index must be <= ",
-        to<string>(highestIndex), " for addresses of type :",
+    throw std::invalid_argument(sformat(
+        "Byte index must be <= {} for addresses of type: {}",
+        highestIndex,
         detail::familyNameStr(AF_INET6)));
   }
   return bytes()[byteIndex];
index 8db2e6d3c70b85b1514b061bc4f8b610bf1ca586..2ee684b180d6a99f886325cf18e554072e0a65ec 100644 (file)
@@ -19,6 +19,7 @@
 #include <ostream>
 
 #include <folly/Exception.h>
+#include <folly/Format.h>
 #include <folly/IPAddressV6.h>
 #include <folly/String.h>
 
@@ -80,24 +81,24 @@ void MacAddress::parse(StringPiece str) {
   auto p = str.begin();
   for (unsigned int byteIndex = 0; byteIndex < SIZE; ++byteIndex) {
     if (p == str.end()) {
-      throw invalid_argument(to<string>("invalid MAC address \"", str,
-                                        "\": not enough digits"));
+      throw invalid_argument(
+          sformat("invalid MAC address '{}': not enough digits", str));
     }
 
     // Skip over ':' or '-' separators between bytes
     if (byteIndex != 0 && isSeparatorChar(*p)) {
       ++p;
       if (p == str.end()) {
-        throw invalid_argument(to<string>("invalid MAC address \"", str,
-                                          "\": not enough digits"));
+        throw invalid_argument(
+            sformat("invalid MAC address '{}': not enough digits", str));
       }
     }
 
     // Parse the upper nibble
     uint8_t upper = detail::hexTable[static_cast<uint8_t>(*p)];
     if (upper & 0x10) {
-      throw invalid_argument(to<string>("invalid MAC address \"", str,
-                                        "\": contains non-hex digit"));
+      throw invalid_argument(
+          sformat("invalid MAC address '{}': contains non-hex digit", str));
     }
     ++p;
 
@@ -115,8 +116,8 @@ void MacAddress::parse(StringPiece str) {
           lower = upper;
           upper = 0;
         } else {
-          throw invalid_argument(to<string>("invalid MAC address \"", str,
-                                            "\": contains non-hex digit"));
+          throw invalid_argument(
+              sformat("invalid MAC address '{}': contains non-hex digit", str));
         }
       }
       ++p;
@@ -128,8 +129,8 @@ void MacAddress::parse(StringPiece str) {
 
   if (p != str.end()) {
     // String is too long to be a MAC address
-    throw invalid_argument(to<string>("invalid MAC address \"", str,
-                                      "\": found trailing characters"));
+    throw invalid_argument(
+        sformat("invalid MAC address '{}': found trailing characters", str));
   }
 
   // Only update now that we have successfully parsed the entire
@@ -139,8 +140,8 @@ void MacAddress::parse(StringPiece str) {
 
 void MacAddress::setFromBinary(ByteRange value) {
   if (value.size() != SIZE) {
-    throw invalid_argument(to<string>("MAC address must be 6 bytes "
-                                      "long, got ", value.size()));
+    throw invalid_argument(
+        sformat("MAC address must be 6 bytes long, got ", value.size()));
   }
   memcpy(bytes_ + 2, value.begin(), SIZE);
 }
index 0209555c19bac1b813c80ea6273587d417e09bc0..a07b02f1948b7513542e477de2963f2fc328cfc7 100644 (file)
@@ -31,6 +31,7 @@
 
 #include <folly/CppAttributes.h>
 #include <folly/Exception.h>
+#include <folly/Format.h>
 #include <folly/Hash.h>
 
 namespace {
@@ -625,9 +626,11 @@ struct addrinfo* SocketAddress::getAddrInfo(const char* host,
   struct addrinfo *results;
   int error = getaddrinfo(host, port, &hints, &results);
   if (error != 0) {
-    auto os = folly::to<std::string>(
-      "Failed to resolve address for \"", host,  "\": ",
-      gai_strerror(error), " (error=", error,  ")");
+    auto os = folly::sformat(
+        "Failed to resolve address for '{}': {} (error={})",
+        host,
+        gai_strerror(error),
+        error);
     throw std::system_error(error, std::generic_category(), os);
   }
 
@@ -685,9 +688,8 @@ void SocketAddress::getIpString(char *buf, size_t buflen, int flags) const {
   int rc = getnameinfo((sockaddr*)&tmp_sock, sizeof(sockaddr_storage),
                        buf, buflen, nullptr, 0, flags);
   if (rc != 0) {
-    auto os = folly::to<std::string>(
-      "getnameinfo() failed in getIpString() error = ",
-      gai_strerror(rc));
+    auto os = sformat(
+        "getnameinfo() failed in getIpString() error = {}", gai_strerror(rc));
     throw std::system_error(rc, std::generic_category(), os);
   }
 }
index a830e1334480287ef4dfe169c0a1873b4907063a..3076f29b878401d36edfb4aaa5da59e348e02ae0 100644 (file)
 namespace folly { namespace detail {
 
 std::string familyNameStrDefault(sa_family_t family) {
-  return folly::sformat("sa_family_t({})", folly::to<std::string>(family));
+  return sformat("sa_family_t({})", family);
 }
 
 [[noreturn]] void getNthMSBitImplThrow(size_t bitCount, sa_family_t family) {
-  throw std::invalid_argument(folly::to<std::string>(
-      "Bit index must be < ",
+  throw std::invalid_argument(sformat(
+      "Bit index must be < {} for addresses of type: {}",
       bitCount,
-      " for addresses of type :",
       familyNameStr(family)));
 }
 
index 7f08f8440822ceeac3540f5d4ba57890cc6c8126..f9e374ee80ace6aaf6bf08188844706044ccf606 100644 (file)
@@ -24,7 +24,7 @@
 #include <string>
 #include <type_traits>
 
-#include <folly/Conv.h>
+#include <folly/Format.h>
 #include <folly/detail/IPAddress.h>
 
 // BSDish platforms don't provide standard access to s6_addr16
@@ -74,11 +74,9 @@ struct Bytes {
         0xff // /8
     }};
     if (oneMask > kBitCount || twoMask > kBitCount) {
-      throw std::invalid_argument(folly::to<std::string>(
-          "Invalid mask "
-          "length: ",
-          oneMask > twoMask ? oneMask : twoMask,
-          ". Mask length must be <= ",
+      throw std::invalid_argument(sformat(
+          "Invalid mask length: {}. Mask length must be <= {}",
+          std::max(oneMask, twoMask),
           kBitCount));
     }
 
index 3099aa7db0fe2a7b2d4ea34ad14ad1024ac9ab5f..254c725fa8287cdca8237487d74072059cae7ed3 100644 (file)
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-#include <folly/Conv.h>
+#include <folly/Format.h>
 #include <folly/IPAddress.h>
 
 #include <glog/logging.h>
@@ -50,7 +50,7 @@ BENCHMARK_DRAW_LINE()
 BENCHMARK(ipv4_to_fully_qualified_port, iters) {
   IPAddressV4 ip("255.255.255.255");
   while (iters--) {
-    string outputString = to<std::string>(ip.toFullyQualified(), ':', 65535);
+    string outputString = folly::sformat("{}:{}", ip.toFullyQualified(), 65535);
     folly::doNotOptimizeAway(outputString);
     folly::doNotOptimizeAway(outputString.data());
   }
@@ -99,7 +99,7 @@ BENCHMARK_DRAW_LINE()
 BENCHMARK(ipv6_to_fully_qualified_port, iters) {
   IPAddressV6 ip("F1E0:0ACE:FB94:7ADF:22E8:6DE6:9672:3725");
   while (iters--) {
-    string outputString = to<std::string>(ip.toFullyQualified(), ':', 65535);
+    string outputString = folly::sformat("{}:{}", ip.toFullyQualified(), 65535);
     folly::doNotOptimizeAway(outputString);
     folly::doNotOptimizeAway(outputString.data());
   }
index a372120d4b11caa0f4876de25622a20c0ab794d6..5417dd60632619006ad5c3876ce3a91233c2e438 100644 (file)
@@ -781,8 +781,7 @@ TEST(IPAddress, V6Types) {
         EXPECT_FALSE(ipv6.isTeredo()) << "isTeredo was true";
         break;
       default:
-        throw std::range_error("Invalid expected type: " +
-                               folly::to<std::string>(tc.second));
+        FAIL() << "Invalid expected type: " << to<std::string>(tc.second);
     }
   }
 }
index 2f701738ec86aa76c8a831370d791b5214ac7348..6f013ea60624f27999766c53d1426c0b80a4a970 100644 (file)
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-#include <folly/Conv.h>
+#include <folly/Format.h>
 #include <folly/IPAddressV6.h>
 #include <folly/MacAddress.h>
 #include <folly/portability/GTest.h>
@@ -138,7 +138,7 @@ TEST(MacAddress, createMulticast) {
 }
 
 void testCmp(const char* str1, const char* str2) {
-  SCOPED_TRACE(folly::to<std::string>(str1, " < ", str2));
+  SCOPED_TRACE(folly::sformat("{} < {}", str1, str2));
   MacAddress m1(str1);
   MacAddress m2(str2);