makeFutureTry -> makeFutureWith
[folly.git] / folly / futures / Future-inl.h
index 893aa020f7ede3e89cef2c573d019da814809ccb..135440a9e1ebfc49569c54bcb492c0884fb04833 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2014 Facebook, Inc.
+ * Copyright 2015 Facebook, Inc.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -19,7 +19,8 @@
 #include <chrono>
 #include <thread>
 
-#include <folly/Baton.h>
+#include <folly/experimental/fibers/Baton.h>
+#include <folly/Optional.h>
 #include <folly/futures/detail/Core.h>
 #include <folly/futures/Timekeeper.h>
 
@@ -32,33 +33,21 @@ namespace detail {
 }
 
 template <class T>
-Future<T>::Future(Future<T>&& other) noexcept : core_(nullptr) {
-  *this = std::move(other);
+Future<T>::Future(Future<T>&& other) noexcept : core_(other.core_) {
+  other.core_ = nullptr;
 }
 
 template <class T>
-Future<T>& Future<T>::operator=(Future<T>&& other) {
+Future<T>& Future<T>::operator=(Future<T>&& other) noexcept {
   std::swap(core_, other.core_);
   return *this;
 }
 
 template <class T>
-template <class F>
-Future<T>::Future(
-  const typename std::enable_if<!std::is_void<F>::value, F>::type& val)
-    : core_(nullptr) {
-  Promise<F> p;
-  p.setValue(val);
-  *this = p.getFuture();
-}
-
-template <class T>
-template <class F>
-Future<T>::Future(
-  typename std::enable_if<!std::is_void<F>::value, F>::type&& val)
-    : core_(nullptr) {
-  Promise<F> p;
-  p.setValue(std::forward<F>(val));
+template <class T2>
+Future<T>::Future(T2&& val) : core_(nullptr) {
+  Promise<T> p;
+  p.setValue(std::forward<T2>(val));
   *this = p.getFuture();
 }
 
@@ -98,6 +87,20 @@ void Future<T>::setCallback_(F&& func) {
   core_->setCallback(std::move(func));
 }
 
+// unwrap
+
+template <class T>
+template <class F>
+typename std::enable_if<isFuture<F>::value,
+                        Future<typename isFuture<T>::Inner>>::type
+Future<T>::unwrap() {
+  return then([](Future<typename isFuture<T>::Inner> internal_future) {
+      return internal_future;
+  });
+}
+
+// then
+
 // Variant: returns a value
 // e.g. f.then([](Try<T>&& t){ return t.value(); });
 template <class T>
@@ -115,6 +118,9 @@ Future<T>::thenImplementation(F func, detail::argResult<isTry, F, Args...>) {
 
   // grab the Future now before we lose our handle on the Promise
   auto f = p->getFuture();
+  if (getExecutor()) {
+    f.setExecutor(getExecutor());
+  }
 
   /* This is a bit tricky.
 
@@ -153,7 +159,7 @@ Future<T>::thenImplementation(F func, detail::argResult<isTry, F, Args...>) {
       if (!isTry && t.hasException()) {
         p->setException(std::move(t.exception()));
       } else {
-        p->fulfil([&]() {
+        p->setWith([&]() {
           return (*funcm)(t.template get<isTry, Args>()...);
         });
       }
@@ -179,6 +185,9 @@ Future<T>::thenImplementation(F func, detail::argResult<isTry, F, Args...>) {
 
   // grab the Future now before we lose our handle on the Promise
   auto f = p->getFuture();
+  if (getExecutor()) {
+    f.setExecutor(getExecutor());
+  }
 
   setCallback_(
     [p, funcm](Try<T>&& t) mutable {
@@ -189,9 +198,11 @@ Future<T>::thenImplementation(F func, detail::argResult<isTry, F, Args...>) {
           auto f2 = (*funcm)(t.template get<isTry, Args>()...);
           // that didn't throw, now we can steal p
           f2.setCallback_([p](Try<B>&& b) mutable {
-            p->fulfilTry(std::move(b));
+            p->setTry(std::move(b));
           });
         } catch (const std::exception& e) {
+          p->setException(exception_wrapper(std::current_exception(), e));
+        } catch (...) {
           p->setException(exception_wrapper(std::current_exception()));
         }
       }
@@ -201,9 +212,9 @@ Future<T>::thenImplementation(F func, detail::argResult<isTry, F, Args...>) {
 }
 
 template <typename T>
-template <typename Caller, typename R, typename... Args>
+template <typename R, typename Caller, typename... Args>
   Future<typename isFuture<R>::Inner>
-Future<T>::then(Caller *instance, R(Caller::*func)(Args...)) {
+Future<T>::then(R(Caller::*func)(Args...), Caller *instance) {
   typedef typename std::remove_cv<
     typename std::remove_reference<
       typename detail::ArgType<Args...>::FirstArg>::type>::type FirstArg;
@@ -212,6 +223,19 @@ Future<T>::then(Caller *instance, R(Caller::*func)(Args...)) {
   });
 }
 
+// TODO(6838553)
+#ifndef __clang__
+template <class T>
+template <class... Args>
+auto Future<T>::then(Executor* x, Args&&... args)
+  -> decltype(this->then(std::forward<Args>(args)...))
+{
+  auto oldX = getExecutor();
+  setExecutor(x);
+  return this->then(std::forward<Args>(args)...).via(oldX);
+}
+#endif
+
 template <class T>
 Future<void> Future<T>::then() {
   return then([] (Try<T>&& t) {});
@@ -221,6 +245,7 @@ Future<void> Future<T>::then() {
 template <class T>
 template <class F>
 typename std::enable_if<
+  !detail::callableWith<F, exception_wrapper>::value &&
   !detail::Extract<F>::ReturnsFuture::value,
   Future<T>>::type
 Future<T>::onError(F&& func) {
@@ -235,11 +260,11 @@ Future<T>::onError(F&& func) {
   auto funcm = folly::makeMoveWrapper(std::move(func));
   setCallback_([pm, funcm](Try<T>&& t) mutable {
     if (!t.template withException<Exn>([&] (Exn& e) {
-          pm->fulfil([&]{
+          pm->setWith([&]{
             return (*funcm)(e);
           });
         })) {
-      pm->fulfilTry(std::move(t));
+      pm->setTry(std::move(t));
     }
   });
 
@@ -250,6 +275,7 @@ Future<T>::onError(F&& func) {
 template <class T>
 template <class F>
 typename std::enable_if<
+  !detail::callableWith<F, exception_wrapper>::value &&
   detail::Extract<F>::ReturnsFuture::value,
   Future<T>>::type
 Future<T>::onError(F&& func) {
@@ -267,7 +293,7 @@ Future<T>::onError(F&& func) {
           try {
             auto f2 = (*funcm)(e);
             f2.setCallback_([pm](Try<T>&& t2) mutable {
-              pm->fulfilTry(std::move(t2));
+              pm->setTry(std::move(t2));
             });
           } catch (const std::exception& e2) {
             pm->setException(exception_wrapper(std::current_exception(), e2));
@@ -275,7 +301,89 @@ Future<T>::onError(F&& func) {
             pm->setException(exception_wrapper(std::current_exception()));
           }
         })) {
-      pm->fulfilTry(std::move(t));
+      pm->setTry(std::move(t));
+    }
+  });
+
+  return f;
+}
+
+template <class T>
+template <class F>
+Future<T> Future<T>::ensure(F func) {
+  MoveWrapper<F> funcw(std::move(func));
+  return this->then([funcw](Try<T>&& t) {
+    (*funcw)();
+    return makeFuture(std::move(t));
+  });
+}
+
+template <class T>
+template <class F>
+Future<T> Future<T>::onTimeout(Duration dur, F&& func, Timekeeper* tk) {
+  auto funcw = folly::makeMoveWrapper(std::forward<F>(func));
+  return within(dur, tk)
+    .onError([funcw](TimedOut const&) { return (*funcw)(); });
+}
+
+template <class T>
+template <class F>
+typename std::enable_if<
+  detail::callableWith<F, exception_wrapper>::value &&
+  detail::Extract<F>::ReturnsFuture::value,
+  Future<T>>::type
+Future<T>::onError(F&& func) {
+  static_assert(
+      std::is_same<typename detail::Extract<F>::Return, Future<T>>::value,
+      "Return type of onError callback must be T or Future<T>");
+
+  Promise<T> p;
+  auto f = p.getFuture();
+  auto pm = folly::makeMoveWrapper(std::move(p));
+  auto funcm = folly::makeMoveWrapper(std::move(func));
+  setCallback_([pm, funcm](Try<T> t) mutable {
+    if (t.hasException()) {
+      try {
+        auto f2 = (*funcm)(std::move(t.exception()));
+        f2.setCallback_([pm](Try<T> t2) mutable {
+          pm->setTry(std::move(t2));
+        });
+      } catch (const std::exception& e2) {
+        pm->setException(exception_wrapper(std::current_exception(), e2));
+      } catch (...) {
+        pm->setException(exception_wrapper(std::current_exception()));
+      }
+    } else {
+      pm->setTry(std::move(t));
+    }
+  });
+
+  return f;
+}
+
+// onError(exception_wrapper) that returns T
+template <class T>
+template <class F>
+typename std::enable_if<
+  detail::callableWith<F, exception_wrapper>::value &&
+  !detail::Extract<F>::ReturnsFuture::value,
+  Future<T>>::type
+Future<T>::onError(F&& func) {
+  static_assert(
+      std::is_same<typename detail::Extract<F>::Return, Future<T>>::value,
+      "Return type of onError callback must be T or Future<T>");
+
+  Promise<T> p;
+  auto f = p.getFuture();
+  auto pm = folly::makeMoveWrapper(std::move(p));
+  auto funcm = folly::makeMoveWrapper(std::move(func));
+  setCallback_([pm, funcm](Try<T> t) mutable {
+    if (t.hasException()) {
+      pm->setWith([&]{
+        return (*funcm)(std::move(t.exception()));
+      });
+    } else {
+      pm->setTry(std::move(t));
     }
   });
 
@@ -303,13 +411,21 @@ Try<T>& Future<T>::getTry() {
   return core_->getTry();
 }
 
+template <class T>
+Optional<Try<T>> Future<T>::poll() {
+  Optional<Try<T>> o;
+  if (core_->ready()) {
+    o = std::move(core_->getTry());
+  }
+  return o;
+}
+
 template <class T>
 template <typename Executor>
 inline Future<T> Future<T>::via(Executor* executor) && {
   throwIfInvalid();
 
-  this->deactivate();
-  core_->setExecutor(executor);
+  setExecutor(executor);
 
   return std::move(*this);
 }
@@ -321,7 +437,7 @@ inline Future<T> Future<T>::via(Executor* executor) & {
 
   MoveWrapper<Promise<T>> p;
   auto f = p->getFuture();
-  then([p](Try<T>&& t) mutable { p->fulfilTry(std::move(t)); });
+  then([p](Try<T>&& t) mutable { p->setTry(std::move(t)); });
   return std::move(f).via(executor);
 }
 
@@ -353,12 +469,12 @@ Future<void> makeFuture() {
 }
 
 template <class F>
-auto makeFutureTry(
+auto makeFutureWith(
     F&& func,
     typename std::enable_if<!std::is_reference<F>::value, bool>::type sdf)
     -> Future<decltype(func())> {
   Promise<decltype(func())> p;
-  p.fulfil(
+  p.setWith(
     [&func]() {
       return (func)();
     });
@@ -366,9 +482,9 @@ auto makeFutureTry(
 }
 
 template <class F>
-auto makeFutureTry(F const& func) -> Future<decltype(func())> {
+auto makeFutureWith(F const& func) -> Future<decltype(func())> {
   F copy = func;
-  return makeFutureTry(std::move(copy));
+  return makeFutureWith(std::move(copy));
 }
 
 template <class T>
@@ -397,7 +513,7 @@ makeFuture(E const& e) {
 template <class T>
 Future<T> makeFuture(Try<T>&& t) {
   Promise<typename std::decay<T>::type> p;
-  p.fulfilTry(std::move(t));
+  p.setTry(std::move(t));
   return p.getFuture();
 }
 
@@ -421,13 +537,12 @@ Future<void> via(Executor* executor) {
 template <typename... Fs>
 typename detail::VariadicContext<
   typename std::decay<Fs>::type::value_type...>::type
-whenAll(Fs&&... fs)
-{
+collectAll(Fs&&... fs) {
   auto ctx =
     new detail::VariadicContext<typename std::decay<Fs>::type::value_type...>();
   ctx->total = sizeof...(fs);
   auto f_saved = ctx->p.getFuture();
-  detail::whenAllVariadicHelper(ctx,
+  detail::collectAllVariadicHelper(ctx,
     std::forward<typename std::decay<Fs>::type>(fs)...);
   return f_saved;
 }
@@ -438,8 +553,7 @@ template <class InputIterator>
 Future<
   std::vector<
   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
-whenAll(InputIterator first, InputIterator last)
-{
+collectAll(InputIterator first, InputIterator last) {
   typedef
     typename std::iterator_traits<InputIterator>::value_type::value_type T;
 
@@ -457,13 +571,139 @@ whenAll(InputIterator first, InputIterator last)
   for (size_t i = 0; first != last; ++first, ++i) {
      assert(i < n);
      auto& f = *first;
-     f.setCallback_([ctx, i, n](Try<T>&& t) {
-         ctx->results[i] = std::move(t);
-         if (++ctx->count == n) {
-           ctx->p.setValue(std::move(ctx->results));
-           delete ctx;
+     f.setCallback_([ctx, i, n](Try<T> t) {
+       ctx->results[i] = std::move(t);
+       if (++ctx->count == n) {
+         ctx->p.setValue(std::move(ctx->results));
+         delete ctx;
+       }
+     });
+  }
+
+  return f_saved;
+}
+
+namespace detail {
+
+template <class, class, typename = void> struct CollectContextHelper;
+
+template <class T, class VecT>
+struct CollectContextHelper<T, VecT,
+    typename std::enable_if<std::is_same<T, VecT>::value>::type> {
+  static inline std::vector<T>&& getResults(std::vector<VecT>& results) {
+    return std::move(results);
+  }
+};
+
+template <class T, class VecT>
+struct CollectContextHelper<T, VecT,
+    typename std::enable_if<!std::is_same<T, VecT>::value>::type> {
+  static inline std::vector<T> getResults(std::vector<VecT>& results) {
+    std::vector<T> finalResults;
+    finalResults.reserve(results.size());
+    for (auto& opt : results) {
+      finalResults.push_back(std::move(opt.value()));
+    }
+    return finalResults;
+  }
+};
+
+template <typename T>
+struct CollectContext {
+
+  typedef typename std::conditional<
+    std::is_default_constructible<T>::value,
+    T,
+    Optional<T>
+   >::type VecT;
+
+  explicit CollectContext(int n) : count(0), threw(false) {
+    results.resize(n);
+  }
+
+  Promise<std::vector<T>> p;
+  std::vector<VecT> results;
+  std::atomic<size_t> count;
+  std::atomic_bool threw;
+
+  typedef std::vector<T> result_type;
+
+  static inline Future<std::vector<T>> makeEmptyFuture() {
+    return makeFuture(std::vector<T>());
+  }
+
+  inline void setValue() {
+    p.setValue(CollectContextHelper<T, VecT>::getResults(results));
+  }
+
+  inline void addResult(int i, Try<T>& t) {
+    results[i] = std::move(t.value());
+  }
+};
+
+template <>
+struct CollectContext<void> {
+
+  explicit CollectContext(int n) : count(0), threw(false) {}
+
+  Promise<void> p;
+  std::atomic<size_t> count;
+  std::atomic_bool threw;
+
+  typedef void result_type;
+
+  static inline Future<void> makeEmptyFuture() {
+    return makeFuture();
+  }
+
+  inline void setValue() {
+    p.setValue();
+  }
+
+  inline void addResult(int i, Try<void>& t) {
+    // do nothing
+  }
+};
+
+} // detail
+
+template <class InputIterator>
+Future<typename detail::CollectContext<
+  typename std::iterator_traits<InputIterator>::value_type::value_type
+>::result_type>
+collect(InputIterator first, InputIterator last) {
+  typedef
+    typename std::iterator_traits<InputIterator>::value_type::value_type T;
+
+  if (first >= last) {
+    return detail::CollectContext<T>::makeEmptyFuture();
+  }
+
+  size_t n = std::distance(first, last);
+  auto ctx = new detail::CollectContext<T>(n);
+  auto f_saved = ctx->p.getFuture();
+
+  for (size_t i = 0; first != last; ++first, ++i) {
+     assert(i < n);
+     auto& f = *first;
+     f.setCallback_([ctx, i, n](Try<T> t) {
+       auto c = ++ctx->count;
+
+       if (t.hasException()) {
+         if (!ctx->threw.exchange(true)) {
+           ctx->p.setException(std::move(t.exception()));
          }
-       });
+       } else if (!ctx->threw) {
+         ctx->addResult(i, t);
+         if (c == n) {
+           ctx->setValue();
+         }
+       }
+
+       if (c == n) {
+         delete ctx;
+       }
+     });
   }
 
   return f_saved;
@@ -475,7 +715,7 @@ Future<
             Try<
               typename
               std::iterator_traits<InputIterator>::value_type::value_type> > >
-whenAny(InputIterator first, InputIterator last) {
+collectAny(InputIterator first, InputIterator last) {
   typedef
     typename std::iterator_traits<InputIterator>::value_type::value_type T;
 
@@ -498,7 +738,7 @@ whenAny(InputIterator first, InputIterator last) {
 template <class InputIterator>
 Future<std::vector<std::pair<size_t, Try<typename
   std::iterator_traits<InputIterator>::value_type::value_type>>>>
-whenN(InputIterator first, InputIterator last, size_t n) {
+collectN(InputIterator first, InputIterator last, size_t n) {
   typedef typename
     std::iterator_traits<InputIterator>::value_type::value_type T;
   typedef std::vector<std::pair<size_t, Try<T>>> V;
@@ -512,7 +752,7 @@ whenN(InputIterator first, InputIterator last, size_t n) {
   ctx->completed = 0;
 
   // for each completed Future, increase count and add to vector, until we
-  // have n completed futures at which point we fulfil our Promise with the
+  // have n completed futures at which point we fulfill our Promise with the
   // vector
   auto it = first;
   size_t i = 0;
@@ -524,7 +764,7 @@ whenN(InputIterator first, InputIterator last, size_t n) {
         assert(ctx->v.size() < n);
         v.push_back(std::make_pair(i, std::move(t)));
         if (c == n) {
-          ctx->p.fulfilTry(Try<V>(std::move(v)));
+          ctx->p.setTry(Try<V>(std::move(v)));
         }
       }
     });
@@ -540,94 +780,51 @@ whenN(InputIterator first, InputIterator last, size_t n) {
   return ctx->p.getFuture();
 }
 
-namespace {
-  template <class T>
-  void getWaitHelper(Future<T>* f) {
-    // If we already have a value do the cheap thing
-    if (f->isReady()) {
-      return;
-    }
+template <class It, class T, class F, class ItT, class Arg>
+typename std::enable_if<!isFutureResult<F, T, Arg>::value, Future<T>>::type
+reduce(It first, It last, T initial, F func) {
+  if (first == last) {
+    return makeFuture(std::move(initial));
+  }
 
-    folly::Baton<> baton;
-    f->then([&](Try<T> const&) {
-      baton.post();
-    });
-    baton.wait();
-  }
-
-  template <class T>
-  Future<T> getWaitTimeoutHelper(Future<T>* f, Duration dur) {
-    // TODO make and use variadic whenAny #5877971
-    Promise<T> p;
-    auto token = std::make_shared<std::atomic<bool>>();
-    folly::Baton<> baton;
-
-    folly::detail::getTimekeeperSingleton()->after(dur)
-      .then([&,token](Try<void> const& t) {
-        if (token->exchange(true) == false) {
-          if (t.hasException()) {
-            p.setException(std::move(t.exception()));
-          } else {
-            p.setException(TimedOut());
-          }
-          baton.post();
-        }
-      });
+  typedef isTry<Arg> IsTry;
 
-    f->then([&, token](Try<T>&& t) {
-      if (token->exchange(true) == false) {
-        p.fulfilTry(std::move(t));
-        baton.post();
+  return collectAll(first, last)
+    .then([initial, func](std::vector<Try<ItT>>& vals) mutable {
+      for (auto& val : vals) {
+        initial = func(std::move(initial),
+                       // Either return a ItT&& or a Try<ItT>&& depending
+                       // on the type of the argument of func.
+                       val.template get<IsTry::value, Arg&&>());
       }
+      return initial;
     });
-
-    baton.wait();
-    return p.getFuture();
-  }
-}
-
-template <class T>
-T Future<T>::get() {
-  getWaitHelper(this);
-
-  // Big assumption here: the then() call above, since it doesn't move out
-  // the value, leaves us with a value to return here. This would be a big
-  // no-no in user code, but I'm invoking internal developer privilege. This
-  // is slightly more efficient (save a move()) especially if there's an
-  // exception (save a throw).
-  return std::move(value());
 }
 
-template <>
-inline void Future<void>::get() {
-  getWaitHelper(this);
-  value();
-}
+template <class It, class T, class F, class ItT, class Arg>
+typename std::enable_if<isFutureResult<F, T, Arg>::value, Future<T>>::type
+reduce(It first, It last, T initial, F func) {
+  if (first == last) {
+    return makeFuture(std::move(initial));
+  }
 
-template <class T>
-T Future<T>::get(Duration dur) {
-  return std::move(getWaitTimeoutHelper(this, dur).value());
-}
+  typedef isTry<Arg> IsTry;
 
-template <>
-inline void Future<void>::get(Duration dur) {
-  getWaitTimeoutHelper(this, dur).value();
-}
+  auto f = first->then([initial, func](Try<ItT>& head) mutable {
+    return func(std::move(initial),
+                head.template get<IsTry::value, Arg&&>());
+  });
 
-template <class T>
-T Future<T>::getVia(DrivableExecutor* e) {
-  while (!isReady()) {
-    e->drive();
+  for (++first; first != last; ++first) {
+    f = collectAll(f, *first).then([func](std::tuple<Try<T>, Try<ItT>>& t) {
+      return func(std::move(std::get<0>(t).value()),
+                  // Either return a ItT&& or a Try<ItT>&& depending
+                  // on the type of the argument of func.
+                  std::get<1>(t).template get<IsTry::value, Arg&&>());
+    });
   }
-  return std::move(value());
-}
 
-template <>
-inline void Future<void>::getVia(DrivableExecutor* e) {
-  while (!isReady()) {
-    e->drive();
-  }
-  value();
+  return f;
 }
 
 template <class T>
@@ -664,7 +861,7 @@ Future<T> Future<T>::within(Duration dur, E e, Timekeeper* tk) {
 
   this->then([ctx](Try<T>&& t) {
     if (ctx->token.exchange(true) == false) {
-      ctx->promise.fulfilTry(std::move(t));
+      ctx->promise.setTry(std::move(t));
     }
   });
 
@@ -673,66 +870,201 @@ Future<T> Future<T>::within(Duration dur, E e, Timekeeper* tk) {
 
 template <class T>
 Future<T> Future<T>::delayed(Duration dur, Timekeeper* tk) {
-  return whenAll(*this, futures::sleep(dur, tk))
+  return collectAll(*this, futures::sleep(dur, tk))
     .then([](std::tuple<Try<T>, Try<void>> tup) {
       Try<T>& t = std::get<0>(tup);
       return makeFuture<T>(std::move(t));
     });
 }
 
+namespace detail {
+
 template <class T>
-Future<T> Future<T>::wait() {
-  Baton<> baton;
-  auto done = then([&](Try<T> t) {
+void waitImpl(Future<T>& f) {
+  // short-circuit if there's nothing to do
+  if (f.isReady()) return;
+
+  folly::fibers::Baton baton;
+  f = f.then([&](Try<T> t) {
     baton.post();
     return makeFuture(std::move(t));
   });
   baton.wait();
-  while (!done.isReady()) {
-    // There's a race here between the return here and the actual finishing of
-    // the future. f is completed, but the setup may not have finished on done
-    // after the baton has posted.
+
+  // There's a race here between the return here and the actual finishing of
+  // the future. f is completed, but the setup may not have finished on done
+  // after the baton has posted.
+  while (!f.isReady()) {
     std::this_thread::yield();
   }
-  return done;
 }
 
 template <class T>
-Future<T> Future<T>::wait(Duration dur) {
-  auto baton = std::make_shared<Baton<>>();
-  auto done = then([baton](Try<T> t) {
+void waitImpl(Future<T>& f, Duration dur) {
+  // short-circuit if there's nothing to do
+  if (f.isReady()) return;
+
+  auto baton = std::make_shared<folly::fibers::Baton>();
+  f = f.then([baton](Try<T> t) {
     baton->post();
     return makeFuture(std::move(t));
   });
+
   // Let's preserve the invariant that if we did not timeout (timed_wait returns
   // true), then the returned Future is complete when it is returned to the
   // caller. We need to wait out the race for that Future to complete.
-  if (baton->timed_wait(std::chrono::system_clock::now() + dur)) {
-    while (!done.isReady()) {
+  if (baton->timed_wait(dur)) {
+    while (!f.isReady()) {
       std::this_thread::yield();
     }
   }
-  return done;
 }
 
 template <class T>
-Future<T>& Future<T>::waitVia(DrivableExecutor* e) & {
-  while (!isReady()) {
+void waitViaImpl(Future<T>& f, DrivableExecutor* e) {
+  while (!f.isReady()) {
     e->drive();
   }
+}
+
+} // detail
+
+template <class T>
+Future<T>& Future<T>::wait() & {
+  detail::waitImpl(*this);
   return *this;
 }
 
 template <class T>
-Future<T> Future<T>::waitVia(DrivableExecutor* e) && {
-  while (!isReady()) {
-    e->drive();
-  }
+Future<T>&& Future<T>::wait() && {
+  detail::waitImpl(*this);
   return std::move(*this);
 }
 
+template <class T>
+Future<T>& Future<T>::wait(Duration dur) & {
+  detail::waitImpl(*this, dur);
+  return *this;
 }
 
+template <class T>
+Future<T>&& Future<T>::wait(Duration dur) && {
+  detail::waitImpl(*this, dur);
+  return std::move(*this);
+}
+
+template <class T>
+Future<T>& Future<T>::waitVia(DrivableExecutor* e) & {
+  detail::waitViaImpl(*this, e);
+  return *this;
+}
+
+template <class T>
+Future<T>&& Future<T>::waitVia(DrivableExecutor* e) && {
+  detail::waitViaImpl(*this, e);
+  return std::move(*this);
+}
+
+template <class T>
+T Future<T>::get() {
+  return std::move(wait().value());
+}
+
+template <>
+inline void Future<void>::get() {
+  wait().value();
+}
+
+template <class T>
+T Future<T>::get(Duration dur) {
+  wait(dur);
+  if (isReady()) {
+    return std::move(value());
+  } else {
+    throw TimedOut();
+  }
+}
+
+template <>
+inline void Future<void>::get(Duration dur) {
+  wait(dur);
+  if (isReady()) {
+    return;
+  } else {
+    throw TimedOut();
+  }
+}
+
+template <class T>
+T Future<T>::getVia(DrivableExecutor* e) {
+  return std::move(waitVia(e).value());
+}
+
+template <>
+inline void Future<void>::getVia(DrivableExecutor* e) {
+  waitVia(e).value();
+}
+
+template <class T>
+Future<bool> Future<T>::willEqual(Future<T>& f) {
+  return collectAll(*this, f).then([](const std::tuple<Try<T>, Try<T>>& t) {
+    if (std::get<0>(t).hasValue() && std::get<1>(t).hasValue()) {
+      return std::get<0>(t).value() == std::get<1>(t).value();
+    } else {
+      return false;
+      }
+  });
+}
+
+template <class T>
+template <class F>
+Future<T> Future<T>::filter(F predicate) {
+  auto p = folly::makeMoveWrapper(std::move(predicate));
+  return this->then([p](T val) {
+    T const& valConstRef = val;
+    if (!(*p)(valConstRef)) {
+      throw PredicateDoesNotObtain();
+    }
+    return val;
+  });
+}
+
+namespace futures {
+  namespace {
+    template <class Z>
+    Future<Z> chainHelper(Future<Z> f) {
+      return f;
+    }
+
+    template <class Z, class F, class Fn, class... Callbacks>
+    Future<Z> chainHelper(F f, Fn fn, Callbacks... fns) {
+      return chainHelper<Z>(f.then(fn), fns...);
+    }
+  }
+
+  template <class A, class Z, class... Callbacks>
+  std::function<Future<Z>(Try<A>)>
+  chain(Callbacks... fns) {
+    MoveWrapper<Promise<A>> pw;
+    MoveWrapper<Future<Z>> fw(chainHelper<Z>(pw->getFuture(), fns...));
+    return [=](Try<A> t) mutable {
+      pw->setTry(std::move(t));
+      return std::move(*fw);
+    };
+  }
+
+  template <class It, class F, class ItT, class Result>
+  std::vector<Future<Result>> map(It first, It last, F func) {
+    std::vector<Future<Result>> results;
+    for (auto it = first; it != last; it++) {
+      results.push_back(it->then(func));
+    }
+    return results;
+  }
+}
+
+} // namespace folly
+
 // I haven't included a Future<T&> specialization because I don't forsee us
 // using it, however it is not difficult to add when needed. Refer to
 // Future<void> for guidance. std::future and boost::future code would also be