folly/futures: replace MoveWrappers with generalised lambda capture
[folly.git] / folly / futures / detail / Core.h
index 0265159120a5b4b30a085c24e699a4c9458ccf02..a41059009d48cf87d8b600e530141ad2a2bcfd98 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2015 Facebook, Inc.
+ * Copyright 2016 Facebook, Inc.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
 #include <stdexcept>
 #include <vector>
 
+#include <folly/Executor.h>
+#include <folly/Function.h>
+#include <folly/MicroSpinLock.h>
 #include <folly/Optional.h>
-#include <folly/SmallLocks.h>
-
-#include <folly/futures/Try.h>
-#include <folly/futures/Promise.h>
 #include <folly/futures/Future.h>
-#include <folly/Executor.h>
+#include <folly/futures/Promise.h>
+#include <folly/futures/Try.h>
 #include <folly/futures/detail/FSM.h>
 
 #include <folly/io/async/Request.h>
@@ -74,11 +74,13 @@ enum class State : uint8_t {
 /// time there won't be any problems.
 template<typename T>
 class Core {
+  static_assert(!std::is_void<T>::value,
+                "void futures are not supported. Use Unit instead.");
  public:
   /// This must be heap-constructed. There's probably a way to enforce that in
   /// code but since this is just internal detail code and I don't know how
   /// off-hand, I'm punting.
-  Core() {}
+  Core() : result_(), fsm_(State::Start), attached_(2) {}
 
   explicit Core(Try<T>&& t)
     : result_(std::move(t)),
@@ -97,6 +99,26 @@ class Core {
   Core(Core&&) noexcept = delete;
   Core& operator=(Core&&) = delete;
 
+  // Core is assumed to be convertible only if the type is convertible
+  // and the size is the same. This is a compromise for the complexity
+  // of having to make Core truly have a conversion constructor which
+  // would cause various other problems.
+  // If we made Core move constructible then we would need to update the
+  // Promise and Future with the location of the new Core. This is complex
+  // and may be inefficient.
+  // Core should only be modified so that for size(T) == size(U),
+  // sizeof(Core<T>) == size(Core<U>).
+  // This assumption is used as a proxy to make sure that
+  // the members of Core<T> and Core<U> line up so that we can use a
+  // reinterpret cast.
+  template <
+      class U,
+      typename = typename std::enable_if<std::is_convertible<U, T>::value &&
+                                         sizeof(U) == sizeof(T)>::type>
+  static Core<T>* convert(Core<U>* from) {
+    return reinterpret_cast<Core<T>*>(from);
+  }
+
   /// May call from any thread
   bool hasResult() const {
     switch (fsm_.getState()) {
@@ -125,33 +147,13 @@ class Core {
     }
   }
 
-  template <typename F>
-  class LambdaBufHelper {
-   public:
-    explicit LambdaBufHelper(F&& func) : func_(std::forward<F>(func)) {}
-    void operator()(Try<T>&& t) {
-      SCOPE_EXIT { this->~LambdaBufHelper(); };
-      func_(std::move(t));
-    }
-   private:
-    F func_;
-  };
-
   /// Call only from Future thread.
   template <typename F>
-  void setCallback(F func) {
+  void setCallback(F&& func) {
     bool transitionToArmed = false;
     auto setCallback_ = [&]{
       context_ = RequestContext::saveContext();
-
-      // Move the lambda into the Core if it fits
-      if (sizeof(LambdaBufHelper<F>) <= lambdaBufSize) {
-        auto funcLoc = static_cast<LambdaBufHelper<F>*>((void*)lambdaBuf_);
-        new (funcLoc) LambdaBufHelper<F>(std::forward<F>(func));
-        callback_ = std::ref(*funcLoc);
-      } else {
-        callback_ = std::move(func);
-      }
+      callback_ = std::forward<F>(func);
     };
 
     FSM_START(fsm_)
@@ -213,7 +215,7 @@ class Core {
     // detachPromise() and setResult() should never be called in parallel
     // so we don't need to protect this.
     if (UNLIKELY(!result_)) {
-      setResult(Try<T>(exception_wrapper(BrokenPromise())));
+      setResult(Try<T>(exception_wrapper(BrokenPromise(typeid(T).name()))));
     }
     detachOne();
   }
@@ -313,8 +315,6 @@ class Core {
   }
 
   void doCallback() {
-    RequestContext::setContext(context_);
-
     Executor* x = executor_;
     int8_t priority;
     if (x) {
@@ -326,26 +326,37 @@ class Core {
       executorLock_.unlock();
     }
 
+    // keep Core alive until callback did its thing
+    ++attached_;
+
     if (x) {
-      // keep Core alive until executor did its thing
-      ++attached_;
       try {
         if (LIKELY(x->getNumPriorities() == 1)) {
           x->add([this]() mutable {
             SCOPE_EXIT { detachOne(); };
+            RequestContext::setContext(context_);
+            SCOPE_EXIT { callback_ = {}; };
             callback_(std::move(*result_));
           });
         } else {
           x->addWithPriority([this]() mutable {
             SCOPE_EXIT { detachOne(); };
+            RequestContext::setContext(context_);
+            SCOPE_EXIT { callback_ = {}; };
             callback_(std::move(*result_));
           }, priority);
         }
       } catch (...) {
+        --attached_; // Account for extra ++attached_ before try
+        RequestContext::setContext(context_);
         result_ = Try<T>(exception_wrapper(std::current_exception()));
+        SCOPE_EXIT { callback_ = {}; };
         callback_(std::move(*result_));
       }
     } else {
+      SCOPE_EXIT { detachOne(); };
+      RequestContext::setContext(context_);
+      SCOPE_EXIT { callback_ = {}; };
       callback_(std::move(*result_));
     }
   }
@@ -359,15 +370,20 @@ class Core {
     }
   }
 
-  // lambdaBuf occupies exactly one cache line
-  static constexpr size_t lambdaBufSize = 8 * sizeof(void*);
-  char lambdaBuf_[lambdaBufSize];
+  // Core should only be modified so that for size(T) == size(U),
+  // sizeof(Core<T>) == size(Core<U>).
+  // See Core::convert for details.
+
+  folly::Function<
+      void(Try<T>&&),
+      folly::FunctionMoveCtor::MAY_THROW,
+      8 * sizeof(void*)>
+      callback_;
   // place result_ next to increase the likelihood that the value will be
   // contained entirely in one cache line
-  folly::Optional<Try<T>> result_ {};
-  std::function<void(Try<T>&&)> callback_ {nullptr};
-  FSM<State> fsm_ {State::Start};
-  std::atomic<unsigned char> attached_ {2};
+  folly::Optional<Try<T>> result_;
+  FSM<State> fsm_;
+  std::atomic<unsigned char> attached_;
   std::atomic<bool> active_ {true};
   std::atomic<bool> interruptHandlerSet_ {false};
   folly::MicroSpinLock interruptLock_ {0};
@@ -404,22 +420,41 @@ struct CollectVariadicContext {
          p.setException(std::move(t.exception()));
        }
      } else if (!threw) {
-       std::get<I>(results) = std::move(t.value());
+       std::get<I>(results) = std::move(t);
      }
   }
   ~CollectVariadicContext() {
     if (!threw.exchange(true)) {
-      p.setValue(std::move(results));
+      p.setValue(unwrap(std::move(results)));
     }
   }
   Promise<std::tuple<Ts...>> p;
-  std::tuple<Ts...> results;
-  std::atomic<bool> threw;
+  std::tuple<folly::Try<Ts>...> results;
+  std::atomic<bool> threw {false};
   typedef Future<std::tuple<Ts...>> type;
+
+ private:
+  template <typename... Ts2>
+  static std::tuple<Ts...> unwrap(std::tuple<folly::Try<Ts>...>&& o,
+                                  Ts2&&... ts2) {
+    static_assert(sizeof...(ts2) <
+                  std::tuple_size<std::tuple<folly::Try<Ts>...>>::value,
+                  "Non-templated unwrap should be used instead");
+    assert(std::get<sizeof...(ts2)>(o).hasValue());
+
+    return unwrap(std::move(o),
+                  std::forward<Ts2>(ts2)...,
+                  std::move(*std::get<sizeof...(ts2)>(o)));
+  }
+
+  static std::tuple<Ts...> unwrap(std::tuple<folly::Try<Ts>...>&& /* o */,
+                                  Ts&&... ts) {
+    return std::tuple<Ts...>(std::forward<Ts>(ts)...);
+  }
 };
 
-template <template <typename ...> class T, typename... Ts>
-void collectVariadicHelper(const std::shared_ptr<T<Ts...>>& ctx) {
+template <template <typename...> class T, typename... Ts>
+void collectVariadicHelper(const std::shared_ptr<T<Ts...>>& /* ctx */) {
   // base case
 }