Introduce non-throwing try* methods for IPAddress{,V4,V6}.
authorAndrey Ignatov <rdna@fb.com>
Thu, 2 Nov 2017 17:22:09 +0000 (10:22 -0700)
committerFacebook Github Bot <facebook-github-bot@users.noreply.github.com>
Thu, 2 Nov 2017 17:49:54 +0000 (10:49 -0700)
commit30c1e1dcee8143c6804231a009ae939e5793dc56
treea4dbc7fd9001368692ccca15791320355e068699
parent723d4d3fe6884f9a5057f2057c2a9a6dbc1e3f9a
Introduce non-throwing try* methods for IPAddress{,V4,V6}.

Summary:
Now there is no interface to create `IPAddress{,V4,V6}` from a string or
`ByteRange` that doesn't throw. All available static methods throw
`IPAddressFormatException`.

It has a few disadvantages:

== 1. It's unsafe ==

Caller is not forced to catch exception, it's very easy to write
`IPAddress(potentiallyInvalidString)` and discover that it can throw when it's
already in prod.

== 2. It's inconvenient ==

if caller is aware about exception, (s)he's forced to write `try {} catch` that
is inconvenient and leads to code like this:
  folly::IPAddress taskIp;
  try {
    taskIp = folly::IPAddress(kv.second.taskIp);
  } catch (const folly::IPAddressFormatException&) {
    // Error handling ..
  }
  // Use IP ..

== 3. It's expensive ==

Amended benchmark shows that `IPAddress` constructor is ~10 times slower when a
string with invalid IP is passed to it.

 ---

The diff introduces two non-throwing interfaces for all tree flavors of `IPAddress`:

`tryFromString()` tries to create IP address from string and returns either
corresponding IP address or `enum class IPAddressFormatError` using
`folly::Expected`.

`tryFromBinary()` does same thing but for `ByteRange` input.

The code can be as short as:
  if (auto maybeIp = IPAddress::tryFromString(ipStr)) {
    // Use maybeIp.value() ..
  }

The `try` prefix is chosen to be consistent with other interfaces in folly,
e.g. `to` and `tryTo`.

Reviewed By: yfeldblum

Differential Revision: D6211182

fbshipit-source-id: f27cf90997c100a5fd42138e66ff9bb172204c20
folly/IPAddress.cpp
folly/IPAddress.h
folly/IPAddressException.h
folly/IPAddressV4.cpp
folly/IPAddressV4.h
folly/IPAddressV6.cpp
folly/IPAddressV6.h
folly/test/IPAddressBenchmark.cpp
folly/test/IPAddressTest.cpp