Fix ASAN failure in FutureDAG test
[folly.git] / folly / Function.h
1 /*
2  * Copyright 2017-present Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 /*
17  * @author Eric Niebler (eniebler@fb.com), Sven Over (over@fb.com)
18  * Acknowledgements: Giuseppe Ottaviano (ott@fb.com)
19  */
20
21 /**
22  * @class Function
23  *
24  * @brief A polymorphic function wrapper that is not copyable and does not
25  *    require the wrapped function to be copy constructible.
26  *
27  * `folly::Function` is a polymorphic function wrapper, similar to
28  * `std::function`. The template parameters of the `folly::Function` define
29  * the parameter signature of the wrapped callable, but not the specific
30  * type of the embedded callable. E.g. a `folly::Function<int(int)>`
31  * can wrap callables that return an `int` when passed an `int`. This can be a
32  * function pointer or any class object implementing one or both of
33  *
34  *     int operator(int);
35  *     int operator(int) const;
36  *
37  * If both are defined, the non-const one takes precedence.
38  *
39  * Unlike `std::function`, a `folly::Function` can wrap objects that are not
40  * copy constructible. As a consequence of this, `folly::Function` itself
41  * is not copyable, either.
42  *
43  * Another difference is that, unlike `std::function`, `folly::Function` treats
44  * const-ness of methods correctly. While a `std::function` allows to wrap
45  * an object that only implements a non-const `operator()` and invoke
46  * a const-reference of the `std::function`, `folly::Function` requires you to
47  * declare a function type as const in order to be able to execute it on a
48  * const-reference.
49  *
50  * For example:
51  *
52  *     class Foo {
53  *      public:
54  *       void operator()() {
55  *         // mutates the Foo object
56  *       }
57  *     };
58  *
59  *     class Bar {
60  *       std::function<void(void)> foo_; // wraps a Foo object
61  *      public:
62  *       void mutateFoo() const
63  *       {
64  *         foo_();
65  *       }
66  *     };
67  *
68  * Even though `mutateFoo` is a const-method, so it can only reference `foo_`
69  * as const, it is able to call the non-const `operator()` of the Foo
70  * object that is embedded in the foo_ function.
71  *
72  * `folly::Function` will not allow you to do that. You will have to decide
73  * whether you need to invoke your wrapped callable from a const reference
74  * (like in the example above), in which case it will only wrap a
75  * `operator() const`. If your functor does not implement that,
76  * compilation will fail. If you do not require to be able to invoke the
77  * wrapped function in a const context, you can wrap any functor that
78  * implements either or both of const and non-const `operator()`.
79  *
80  * The template parameter of `folly::Function`, the `FunctionType`, can be
81  * const-qualified. Be aware that the const is part of the function signature.
82  * It does not mean that the function type is a const type.
83  *
84  *   using FunctionType = R(Args...);
85  *   using ConstFunctionType = R(Args...) const;
86  *
87  * In this example, `FunctionType` and `ConstFunctionType` are different
88  * types. `ConstFunctionType` is not the same as `const FunctionType`.
89  * As a matter of fact, trying to use the latter should emit a compiler
90  * warning or error, because it has no defined meaning.
91  *
92  *     // This will not compile:
93  *     folly::Function<void(void) const> func = Foo();
94  *     // because Foo does not have a member function of the form:
95  *     //   void operator()() const;
96  *
97  *     // This will compile just fine:
98  *     folly::Function<void(void)> func = Foo();
99  *     // and it will wrap the existing member function:
100  *     //   void operator()();
101  *
102  * When should a const function type be used? As a matter of fact, you will
103  * probably not need to use const function types very often. See the following
104  * example:
105  *
106  *     class Bar {
107  *       folly::Function<void()> func_;
108  *       folly::Function<void() const> constFunc_;
109  *
110  *       void someMethod() {
111  *         // Can call func_.
112  *         func_();
113  *         // Can call constFunc_.
114  *         constFunc_();
115  *       }
116  *
117  *       void someConstMethod() const {
118  *         // Can call constFunc_.
119  *         constFunc_();
120  *         // However, cannot call func_ because a non-const method cannot
121  *         // be called from a const one.
122  *       }
123  *     };
124  *
125  * As you can see, whether the `folly::Function`'s function type should
126  * be declared const or not is identical to whether a corresponding method
127  * would be declared const or not.
128  *
129  * You only require a `folly::Function` to hold a const function type, if you
130  * intend to invoke it from within a const context. This is to ensure that
131  * you cannot mutate its inner state when calling in a const context.
132  *
133  * This is how the const/non-const choice relates to lambda functions:
134  *
135  *     // Non-mutable lambdas: can be stored in a non-const...
136  *     folly::Function<void(int)> print_number =
137  *       [] (int number) { std::cout << number << std::endl; };
138  *
139  *     // ...as well as in a const folly::Function
140  *     folly::Function<void(int) const> print_number_const =
141  *       [] (int number) { std::cout << number << std::endl; };
142  *
143  *     // Mutable lambda: can only be stored in a non-const folly::Function:
144  *     int number = 0;
145  *     folly::Function<void()> print_number =
146  *       [number] () mutable { std::cout << ++number << std::endl; };
147  *     // Trying to store the above mutable lambda in a
148  *     // `folly::Function<void() const>` would lead to a compiler error:
149  *     // error: no viable conversion from '(lambda at ...)' to
150  *     // 'folly::Function<void () const>'
151  *
152  * Casting between const and non-const `folly::Function`s:
153  * conversion from const to non-const signatures happens implicitly. Any
154  * function that takes a `folly::Function<R(Args...)>` can be passed
155  * a `folly::Function<R(Args...) const>` without explicit conversion.
156  * This is safe, because casting from const to non-const only entails giving
157  * up the ability to invoke the function from a const context.
158  * Casting from a non-const to a const signature is potentially dangerous,
159  * as it means that a function that may change its inner state when invoked
160  * is made possible to call from a const context. Therefore this cast does
161  * not happen implicitly. The function `folly::constCastFunction` can
162  * be used to perform the cast.
163  *
164  *     // Mutable lambda: can only be stored in a non-const folly::Function:
165  *     int number = 0;
166  *     folly::Function<void()> print_number =
167  *       [number] () mutable { std::cout << ++number << std::endl; };
168  *
169  *     // const-cast to a const folly::Function:
170  *     folly::Function<void() const> print_number_const =
171  *       constCastFunction(std::move(print_number));
172  *
173  * When to use const function types?
174  * Generally, only when you need them. When you use a `folly::Function` as a
175  * member of a struct or class, only use a const function signature when you
176  * need to invoke the function from const context.
177  * When passing a `folly::Function` to a function, the function should accept
178  * a non-const `folly::Function` whenever possible, i.e. when it does not
179  * need to pass on or store a const `folly::Function`. This is the least
180  * possible constraint: you can always pass a const `folly::Function` when
181  * the function accepts a non-const one.
182  *
183  * How does the const behaviour compare to `std::function`?
184  * `std::function` can wrap object with non-const invokation behaviour but
185  * exposes them as const. The equivalent behaviour can be achieved with
186  * `folly::Function` like so:
187  *
188  *     std::function<void(void)> stdfunc = someCallable;
189  *
190  *     folly::Function<void(void) const> uniqfunc = constCastFunction(
191  *       folly::Function<void(void)>(someCallable)
192  *     );
193  *
194  * You need to wrap the callable first in a non-const `folly::Function` to
195  * select a non-const invoke operator (or the const one if no non-const one is
196  * present), and then move it into a const `folly::Function` using
197  * `constCastFunction`.
198  * The name of `constCastFunction` should warn you that something
199  * potentially dangerous is happening. As a matter of fact, using
200  * `std::function` always involves this potentially dangerous aspect, which
201  * is why it is not considered fully const-safe or even const-correct.
202  * However, in most of the cases you will not need the dangerous aspect at all.
203  * Either you do not require invokation of the function from a const context,
204  * in which case you do not need to use `constCastFunction` and just
205  * use the inner `folly::Function` in the example above, i.e. just use a
206  * non-const `folly::Function`. Or, you may need invokation from const, but
207  * the callable you are wrapping does not mutate its state (e.g. it is a class
208  * object and implements `operator() const`, or it is a normal,
209  * non-mutable lambda), in which case you can wrap the callable in a const
210  * `folly::Function` directly, without using `constCastFunction`.
211  * Only if you require invokation from a const context of a callable that
212  * may mutate itself when invoked you have to go through the above procedure.
213  * However, in that case what you do is potentially dangerous and requires
214  * the equivalent of a `const_cast`, hence you need to call
215  * `constCastFunction`.
216  */
217
218 #pragma once
219
220 #include <functional>
221 #include <memory>
222 #include <new>
223 #include <type_traits>
224 #include <utility>
225
226 #include <folly/CppAttributes.h>
227 #include <folly/Portability.h>
228 #include <folly/Traits.h>
229 #include <folly/functional/Invoke.h>
230
231 namespace folly {
232
233 template <typename FunctionType>
234 class Function;
235
236 template <typename ReturnType, typename... Args>
237 Function<ReturnType(Args...) const> constCastFunction(
238     Function<ReturnType(Args...)>&&) noexcept;
239
240 #if FOLLY_HAVE_NOEXCEPT_FUNCTION_TYPE
241 template <typename ReturnType, typename... Args>
242 Function<ReturnType(Args...) const noexcept> constCastFunction(
243     Function<ReturnType(Args...) noexcept>&&) noexcept;
244 #endif
245
246 namespace detail {
247 namespace function {
248
249 enum class Op { MOVE, NUKE, FULL, HEAP };
250
251 union Data {
252   void* big;
253   std::aligned_storage<6 * sizeof(void*)>::type tiny;
254 };
255
256 template <typename Fun, typename = Fun*>
257 using IsSmall = Conjunction<
258     std::integral_constant<bool, (sizeof(Fun) <= sizeof(Data::tiny))>,
259     std::is_nothrow_move_constructible<Fun>>;
260 using SmallTag = std::true_type;
261 using HeapTag = std::false_type;
262
263 template <typename T>
264 struct NotFunction : std::true_type {};
265 template <typename T>
266 struct NotFunction<Function<T>> : std::false_type {};
267
268 template <typename T>
269 using EnableIfNotFunction =
270     typename std::enable_if<NotFunction<T>::value>::type;
271
272 struct CoerceTag {};
273
274 template <typename T>
275 bool isNullPtrFn(T* p) {
276   return p == nullptr;
277 }
278 template <typename T>
279 std::false_type isNullPtrFn(T&&) {
280   return {};
281 }
282
283 inline bool uninitNoop(Op, Data*, Data*) {
284   return false;
285 }
286
287 template <typename FunctionType>
288 struct FunctionTraits;
289
290 template <typename ReturnType, typename... Args>
291 struct FunctionTraits<ReturnType(Args...)> {
292   using Call = ReturnType (*)(Data&, Args&&...);
293   using IsConst = std::false_type;
294   using ConstSignature = ReturnType(Args...) const;
295   using NonConstSignature = ReturnType(Args...);
296   using OtherSignature = ConstSignature;
297
298   template <typename F, typename G = typename std::decay<F>::type>
299   using ResultOf = decltype(
300       static_cast<ReturnType>(std::declval<G&>()(std::declval<Args>()...)));
301
302   template <typename Fun>
303   static ReturnType callSmall(Data& p, Args&&... args) {
304     return static_cast<ReturnType>((*static_cast<Fun*>(
305         static_cast<void*>(&p.tiny)))(static_cast<Args&&>(args)...));
306   }
307
308   template <typename Fun>
309   static ReturnType callBig(Data& p, Args&&... args) {
310     return static_cast<ReturnType>(
311         (*static_cast<Fun*>(p.big))(static_cast<Args&&>(args)...));
312   }
313
314   static ReturnType uninitCall(Data&, Args&&...) {
315     throw std::bad_function_call();
316   }
317
318   ReturnType operator()(Args... args) {
319     auto& fn = *static_cast<Function<NonConstSignature>*>(this);
320     return fn.call_(fn.data_, static_cast<Args&&>(args)...);
321   }
322
323   class SharedProxy {
324     std::shared_ptr<Function<NonConstSignature>> sp_;
325
326    public:
327     explicit SharedProxy(Function<NonConstSignature>&& func)
328         : sp_(std::make_shared<Function<NonConstSignature>>(std::move(func))) {}
329     ReturnType operator()(Args&&... args) const {
330       return (*sp_)(static_cast<Args&&>(args)...);
331     }
332   };
333 };
334
335 template <typename ReturnType, typename... Args>
336 struct FunctionTraits<ReturnType(Args...) const> {
337   using Call = ReturnType (*)(Data&, Args&&...);
338   using IsConst = std::true_type;
339   using ConstSignature = ReturnType(Args...) const;
340   using NonConstSignature = ReturnType(Args...);
341   using OtherSignature = NonConstSignature;
342
343   template <typename F, typename G = typename std::decay<F>::type>
344   using ResultOf = decltype(static_cast<ReturnType>(
345       std::declval<const G&>()(std::declval<Args>()...)));
346
347   template <typename Fun>
348   static ReturnType callSmall(Data& p, Args&&... args) {
349     return static_cast<ReturnType>((*static_cast<const Fun*>(
350         static_cast<void*>(&p.tiny)))(static_cast<Args&&>(args)...));
351   }
352
353   template <typename Fun>
354   static ReturnType callBig(Data& p, Args&&... args) {
355     return static_cast<ReturnType>(
356         (*static_cast<const Fun*>(p.big))(static_cast<Args&&>(args)...));
357   }
358
359   static ReturnType uninitCall(Data&, Args&&...) {
360     throw std::bad_function_call();
361   }
362
363   ReturnType operator()(Args... args) const {
364     auto& fn = *static_cast<const Function<ConstSignature>*>(this);
365     return fn.call_(fn.data_, static_cast<Args&&>(args)...);
366   }
367
368   class SharedProxy {
369     std::shared_ptr<Function<ConstSignature>> sp_;
370
371    public:
372     explicit SharedProxy(Function<ConstSignature>&& func)
373         : sp_(std::make_shared<Function<ConstSignature>>(std::move(func))) {}
374     ReturnType operator()(Args&&... args) const {
375       return (*sp_)(static_cast<Args&&>(args)...);
376     }
377   };
378 };
379
380 #if FOLLY_HAVE_NOEXCEPT_FUNCTION_TYPE
381 template <typename ReturnType, typename... Args>
382 struct FunctionTraits<ReturnType(Args...) noexcept> {
383   using Call = ReturnType (*)(Data&, Args&&...) noexcept;
384   using IsConst = std::false_type;
385   using ConstSignature = ReturnType(Args...) const noexcept;
386   using NonConstSignature = ReturnType(Args...) noexcept;
387   using OtherSignature = ConstSignature;
388
389   template <typename F, typename G = typename std::decay<F>::type>
390   using ResultOf = decltype(
391       static_cast<ReturnType>(std::declval<G&>()(std::declval<Args>()...)));
392
393   template <typename Fun>
394   static ReturnType callSmall(Data& p, Args&&... args) noexcept {
395     return static_cast<ReturnType>((*static_cast<Fun*>(
396         static_cast<void*>(&p.tiny)))(static_cast<Args&&>(args)...));
397   }
398
399   template <typename Fun>
400   static ReturnType callBig(Data& p, Args&&... args) noexcept {
401     return static_cast<ReturnType>(
402         (*static_cast<Fun*>(p.big))(static_cast<Args&&>(args)...));
403   }
404
405   static ReturnType uninitCall(Data&, Args&&...) noexcept {
406     throw std::bad_function_call();
407   }
408
409   ReturnType operator()(Args... args) noexcept {
410     auto& fn = *static_cast<Function<NonConstSignature>*>(this);
411     return fn.call_(fn.data_, static_cast<Args&&>(args)...);
412   }
413
414   class SharedProxy {
415     std::shared_ptr<Function<NonConstSignature>> sp_;
416
417    public:
418     explicit SharedProxy(Function<NonConstSignature>&& func)
419         : sp_(std::make_shared<Function<NonConstSignature>>(std::move(func))) {}
420     ReturnType operator()(Args&&... args) const {
421       return (*sp_)(static_cast<Args&&>(args)...);
422     }
423   };
424 };
425
426 template <typename ReturnType, typename... Args>
427 struct FunctionTraits<ReturnType(Args...) const noexcept> {
428   using Call = ReturnType (*)(Data&, Args&&...) noexcept;
429   using IsConst = std::true_type;
430   using ConstSignature = ReturnType(Args...) const noexcept;
431   using NonConstSignature = ReturnType(Args...) noexcept;
432   using OtherSignature = NonConstSignature;
433
434   template <typename F, typename G = typename std::decay<F>::type>
435   using ResultOf = decltype(static_cast<ReturnType>(
436       std::declval<const G&>()(std::declval<Args>()...)));
437
438   template <typename Fun>
439   static ReturnType callSmall(Data& p, Args&&... args) noexcept {
440     return static_cast<ReturnType>((*static_cast<const Fun*>(
441         static_cast<void*>(&p.tiny)))(static_cast<Args&&>(args)...));
442   }
443
444   template <typename Fun>
445   static ReturnType callBig(Data& p, Args&&... args) noexcept {
446     return static_cast<ReturnType>(
447         (*static_cast<const Fun*>(p.big))(static_cast<Args&&>(args)...));
448   }
449
450   static ReturnType uninitCall(Data&, Args&&...) noexcept {
451     throw std::bad_function_call();
452   }
453
454   ReturnType operator()(Args... args) const noexcept {
455     auto& fn = *static_cast<const Function<ConstSignature>*>(this);
456     return fn.call_(fn.data_, static_cast<Args&&>(args)...);
457   }
458
459   class SharedProxy {
460     std::shared_ptr<Function<ConstSignature>> sp_;
461
462    public:
463     explicit SharedProxy(Function<ConstSignature>&& func)
464         : sp_(std::make_shared<Function<ConstSignature>>(std::move(func))) {}
465     ReturnType operator()(Args&&... args) const {
466       return (*sp_)(static_cast<Args&&>(args)...);
467     }
468   };
469 };
470 #endif
471
472 template <typename Fun>
473 bool execSmall(Op o, Data* src, Data* dst) {
474   switch (o) {
475     case Op::MOVE:
476       ::new (static_cast<void*>(&dst->tiny))
477           Fun(std::move(*static_cast<Fun*>(static_cast<void*>(&src->tiny))));
478       FOLLY_FALLTHROUGH;
479     case Op::NUKE:
480       static_cast<Fun*>(static_cast<void*>(&src->tiny))->~Fun();
481       break;
482     case Op::FULL:
483       return true;
484     case Op::HEAP:
485       break;
486   }
487   return false;
488 }
489
490 template <typename Fun>
491 bool execBig(Op o, Data* src, Data* dst) {
492   switch (o) {
493     case Op::MOVE:
494       dst->big = src->big;
495       src->big = nullptr;
496       break;
497     case Op::NUKE:
498       delete static_cast<Fun*>(src->big);
499       break;
500     case Op::FULL:
501     case Op::HEAP:
502       break;
503   }
504   return true;
505 }
506
507 } // namespace function
508 } // namespace detail
509
510 template <typename FunctionType>
511 class Function final : private detail::function::FunctionTraits<FunctionType> {
512   // These utility types are defined outside of the template to reduce
513   // the number of instantiations, and then imported in the class
514   // namespace for convenience.
515   using Data = detail::function::Data;
516   using Op = detail::function::Op;
517   using SmallTag = detail::function::SmallTag;
518   using HeapTag = detail::function::HeapTag;
519   using CoerceTag = detail::function::CoerceTag;
520
521   using Traits = detail::function::FunctionTraits<FunctionType>;
522   using Call = typename Traits::Call;
523   using Exec = bool (*)(Op, Data*, Data*);
524
525   template <typename Fun>
526   using IsSmall = detail::function::IsSmall<Fun>;
527
528   // The `data_` member is mutable to allow `constCastFunction` to work without
529   // invoking undefined behavior. Const-correctness is only violated when
530   // `FunctionType` is a const function type (e.g., `int() const`) and `*this`
531   // is the result of calling `constCastFunction`.
532   mutable Data data_{};
533   Call call_{&Traits::uninitCall};
534   Exec exec_{&detail::function::uninitNoop};
535
536   friend Traits;
537   friend Function<typename Traits::ConstSignature> folly::constCastFunction<>(
538       Function<typename Traits::NonConstSignature>&&) noexcept;
539   friend class Function<typename Traits::OtherSignature>;
540
541   template <typename Fun>
542   Function(Fun&& fun, SmallTag) noexcept {
543     using FunT = typename std::decay<Fun>::type;
544     if (!detail::function::isNullPtrFn(fun)) {
545       ::new (static_cast<void*>(&data_.tiny)) FunT(static_cast<Fun&&>(fun));
546       call_ = &Traits::template callSmall<FunT>;
547       exec_ = &detail::function::execSmall<FunT>;
548     }
549   }
550
551   template <typename Fun>
552   Function(Fun&& fun, HeapTag) {
553     using FunT = typename std::decay<Fun>::type;
554     data_.big = new FunT(static_cast<Fun&&>(fun));
555     call_ = &Traits::template callBig<FunT>;
556     exec_ = &detail::function::execBig<FunT>;
557   }
558
559   template <typename Signature>
560   Function(Function<Signature>&& that, CoerceTag)
561       : Function(static_cast<Function<Signature>&&>(that), HeapTag{}) {}
562
563   Function(
564       Function<typename Traits::OtherSignature>&& that,
565       CoerceTag) noexcept {
566     that.exec_(Op::MOVE, &that.data_, &data_);
567     std::swap(call_, that.call_);
568     std::swap(exec_, that.exec_);
569   }
570
571  public:
572   /**
573    * Default constructor. Constructs an empty Function.
574    */
575   Function() = default;
576
577   // not copyable
578   Function(const Function&) = delete;
579
580 #if __OBJC__
581   // Make sure Objective C blocks are copied
582   template <class ReturnType, class... Args>
583   /*implicit*/ Function(ReturnType (^objCBlock)(Args... args))
584       : Function([blockCopy = (ReturnType (^)(Args...))[objCBlock copy]](
585                      Args... args) { return blockCopy(args...); }){};
586 #endif
587
588   /**
589    * Move constructor
590    */
591   Function(Function&& that) noexcept {
592     that.exec_(Op::MOVE, &that.data_, &data_);
593     std::swap(call_, that.call_);
594     std::swap(exec_, that.exec_);
595   }
596
597   /**
598    * Constructs an empty `Function`.
599    */
600   /* implicit */ Function(std::nullptr_t) noexcept {}
601
602   /**
603    * Constructs a new `Function` from any callable object that is _not_ a
604    * `folly::Function`. This handles function pointers, pointers to static
605    * member functions, `std::reference_wrapper` objects, `std::function`
606    * objects, and arbitrary objects that implement `operator()` if the parameter
607    * signature matches (i.e. it returns an object convertible to `R` when called
608    * with `Args...`).
609    *
610    * \note `typename = ResultOf<Fun>` prevents this overload from being
611    * selected by overload resolution when `fun` is not a compatible function.
612    *
613    * \note The noexcept requires some explanation. IsSmall is true when the
614    * decayed type fits within the internal buffer and is noexcept-movable. But
615    * this ctor might copy, not move. What we need here, if this ctor does a
616    * copy, is that this ctor be noexcept when the copy is noexcept. That is not
617    * checked in IsSmall, and shouldn't be, because once the Function is
618    * constructed, the contained object is never copied. This check is for this
619    * ctor only, in the case that this ctor does a copy.
620    */
621   template <
622       typename Fun,
623       typename = detail::function::EnableIfNotFunction<Fun>,
624       typename = typename Traits::template ResultOf<Fun>>
625   /* implicit */ Function(Fun fun) noexcept(
626       IsSmall<Fun>::value && noexcept(Fun(std::declval<Fun>())))
627       : Function(static_cast<Fun&&>(fun), IsSmall<Fun>{}) {}
628
629   /**
630    * For move-constructing from a `folly::Function<X(Ys...) [const?]>`.
631    * For a `Function` with a `const` function type, the object must be
632    * callable from a `const`-reference, i.e. implement `operator() const`.
633    * For a `Function` with a non-`const` function type, the object will
634    * be called from a non-const reference, which means that it will execute
635    * a non-const `operator()` if it is defined, and falls back to
636    * `operator() const` otherwise.
637    */
638   template <
639       typename Signature,
640       typename = typename Traits::template ResultOf<Function<Signature>>>
641   Function(Function<Signature>&& that) noexcept(
642       noexcept(Function(std::move(that), CoerceTag{})))
643       : Function(std::move(that), CoerceTag{}) {}
644
645   /**
646    * If `ptr` is null, constructs an empty `Function`. Otherwise,
647    * this constructor is equivalent to `Function(std::mem_fn(ptr))`.
648    */
649   template <
650       typename Member,
651       typename Class,
652       // Prevent this overload from being selected when `ptr` is not a
653       // compatible member function pointer.
654       typename = decltype(Function(std::mem_fn((Member Class::*)0)))>
655   /* implicit */ Function(Member Class::*ptr) noexcept {
656     if (ptr) {
657       *this = std::mem_fn(ptr);
658     }
659   }
660
661   ~Function() {
662     exec_(Op::NUKE, &data_, nullptr);
663   }
664
665   Function& operator=(const Function&) = delete;
666
667 #if __OBJC__
668   // Make sure Objective C blocks are copied
669   template <class ReturnType, class... Args>
670   /* implicit */ Function &operator=(ReturnType (^objCBlock)(Args... args)) {
671     (*this) = [blockCopy = (ReturnType (^)(Args...))[objCBlock copy]](
672                   Args... args) { return blockCopy(args...); };
673     return *this;
674   }
675 #endif
676
677   /**
678    * Move assignment operator
679    *
680    * \note Leaves `that` in a valid but unspecified state. If `&that == this`
681    * then `*this` is left in a valid but unspecified state.
682    */
683   Function& operator=(Function&& that) noexcept {
684     // Q: Why is it safe to destroy and reconstruct this object in place?
685     // A: Two reasons: First, `Function` is a final class, so in doing this
686     //    we aren't slicing off any derived parts. And second, the move
687     //    operation is guaranteed not to throw so we always leave the object
688     //    in a valid state.
689     // In the case of self-move (this == &that), this leaves the object in
690     // a default-constructed state. First the object is destroyed, then we
691     // pass the destroyed object to the move constructor. The first thing the
692     // move constructor does is default-construct the object. That object is
693     // "moved" into itself, which is a no-op for a default-constructed Function.
694     this->~Function();
695     ::new (this) Function(std::move(that));
696     return *this;
697   }
698
699   /**
700    * Assigns a callable object to this `Function`. If the operation fails,
701    * `*this` is left unmodified.
702    *
703    * \note `typename = ResultOf<Fun>` prevents this overload from being
704    * selected by overload resolution when `fun` is not a compatible function.
705    */
706   template <typename Fun, typename = decltype(Function(std::declval<Fun>()))>
707   Function& operator=(Fun fun) noexcept(
708       noexcept(/* implicit */ Function(std::declval<Fun>()))) {
709     // Doing this in place is more efficient when we can do so safely.
710     if (noexcept(/* implicit */ Function(std::declval<Fun>()))) {
711       // Q: Why is is safe to destroy and reconstruct this object in place?
712       // A: See the explanation in the move assignment operator.
713       this->~Function();
714       ::new (this) Function(static_cast<Fun&&>(fun));
715     } else {
716       // Construct a temporary and (nothrow) swap.
717       Function(static_cast<Fun&&>(fun)).swap(*this);
718     }
719     return *this;
720   }
721
722   /**
723    * For assigning from a `Function<X(Ys..) [const?]>`.
724    */
725   template <
726       typename Signature,
727       typename = typename Traits::template ResultOf<Function<Signature>>>
728   Function& operator=(Function<Signature>&& that) noexcept(
729       noexcept(Function(std::move(that)))) {
730     return (*this = Function(std::move(that)));
731   }
732
733   /**
734    * Clears this `Function`.
735    */
736   Function& operator=(std::nullptr_t) noexcept {
737     return (*this = Function());
738   }
739
740   /**
741    * If `ptr` is null, clears this `Function`. Otherwise, this assignment
742    * operator is equivalent to `*this = std::mem_fn(ptr)`.
743    */
744   template <typename Member, typename Class>
745   auto operator=(Member Class::*ptr) noexcept
746       // Prevent this overload from being selected when `ptr` is not a
747       // compatible member function pointer.
748       -> decltype(operator=(std::mem_fn(ptr))) {
749     return ptr ? (*this = std::mem_fn(ptr)) : (*this = Function());
750   }
751
752   /**
753    * Call the wrapped callable object with the specified arguments.
754    */
755   using Traits::operator();
756
757   /**
758    * Exchanges the callable objects of `*this` and `that`.
759    */
760   void swap(Function& that) noexcept {
761     std::swap(*this, that);
762   }
763
764   /**
765    * Returns `true` if this `Function` contains a callable, i.e. is
766    * non-empty.
767    */
768   explicit operator bool() const noexcept {
769     return exec_(Op::FULL, nullptr, nullptr);
770   }
771
772   /**
773    * Returns `true` if this `Function` stores the callable on the
774    * heap. If `false` is returned, there has been no additional memory
775    * allocation and the callable is stored inside the `Function`
776    * object itself.
777    */
778   bool hasAllocatedMemory() const noexcept {
779     return exec_(Op::HEAP, nullptr, nullptr);
780   }
781
782   using typename Traits::SharedProxy;
783
784   /**
785    * Move this `Function` into a copyable callable object, of which all copies
786    * share the state.
787    */
788   SharedProxy asSharedProxy() && {
789     return SharedProxy{std::move(*this)};
790   }
791
792   /**
793    * Construct a `std::function` by moving in the contents of this `Function`.
794    * Note that the returned `std::function` will share its state (i.e. captured
795    * data) across all copies you make of it, so be very careful when copying.
796    */
797   std::function<typename Traits::NonConstSignature> asStdFunction() && {
798     return std::move(*this).asSharedProxy();
799   }
800 };
801
802 template <typename FunctionType>
803 void swap(Function<FunctionType>& lhs, Function<FunctionType>& rhs) noexcept {
804   lhs.swap(rhs);
805 }
806
807 template <typename FunctionType>
808 bool operator==(const Function<FunctionType>& fn, std::nullptr_t) {
809   return !fn;
810 }
811
812 template <typename FunctionType>
813 bool operator==(std::nullptr_t, const Function<FunctionType>& fn) {
814   return !fn;
815 }
816
817 template <typename FunctionType>
818 bool operator!=(const Function<FunctionType>& fn, std::nullptr_t) {
819   return !(fn == nullptr);
820 }
821
822 template <typename FunctionType>
823 bool operator!=(std::nullptr_t, const Function<FunctionType>& fn) {
824   return !(nullptr == fn);
825 }
826
827 /**
828  * NOTE: See detailed note about `constCastFunction` at the top of the file.
829  * This is potentially dangerous and requires the equivalent of a `const_cast`.
830  */
831 template <typename ReturnType, typename... Args>
832 Function<ReturnType(Args...) const> constCastFunction(
833     Function<ReturnType(Args...)>&& that) noexcept {
834   return Function<ReturnType(Args...) const>{std::move(that),
835                                              detail::function::CoerceTag{}};
836 }
837
838 template <typename ReturnType, typename... Args>
839 Function<ReturnType(Args...) const> constCastFunction(
840     Function<ReturnType(Args...) const>&& that) noexcept {
841   return std::move(that);
842 }
843
844 #if FOLLY_HAVE_NOEXCEPT_FUNCTION_TYPE
845 template <typename ReturnType, typename... Args>
846 Function<ReturnType(Args...) const noexcept> constCastFunction(
847     Function<ReturnType(Args...) noexcept>&& that) noexcept {
848   return Function<ReturnType(Args...) const noexcept>{
849       std::move(that), detail::function::CoerceTag{}};
850 }
851
852 template <typename ReturnType, typename... Args>
853 Function<ReturnType(Args...) const noexcept> constCastFunction(
854     Function<ReturnType(Args...) const noexcept>&& that) noexcept {
855   return std::move(that);
856 }
857 #endif
858
859 namespace detail {
860 namespace function {
861 template <typename Fun, typename FunctionType, typename = void>
862 struct IsCallableAsImpl : std::false_type {};
863
864 template <typename Fun, typename ReturnType, typename... Args>
865 struct IsCallableAsImpl<
866     Fun,
867     ReturnType(Args...),
868     void_t<typename std::result_of<Fun && (Args && ...)>::type>>
869     : std::is_convertible<
870           typename std::result_of<Fun && (Args && ...)>::type,
871           ReturnType> {};
872
873 template <typename Fun, typename FunctionType>
874 struct IsCallableAs : IsCallableAsImpl<Fun, FunctionType> {};
875 } // namespace function
876 } // namespace detail
877
878 /**
879  * @class FunctionRef
880  *
881  * @brief A reference wrapper for callable objects
882  *
883  * FunctionRef is similar to std::reference_wrapper, but the template parameter
884  * is the function signature type rather than the type of the referenced object.
885  * A folly::FunctionRef is cheap to construct as it contains only a pointer to
886  * the referenced callable and a pointer to a function which invokes the
887  * callable.
888  *
889  * The user of FunctionRef must be aware of the reference semantics: storing a
890  * copy of a FunctionRef is potentially dangerous and should be avoided unless
891  * the referenced object definitely outlives the FunctionRef object. Thus any
892  * function that accepts a FunctionRef parameter should only use it to invoke
893  * the referenced function and not store a copy of it. Knowing that FunctionRef
894  * itself has reference semantics, it is generally okay to use it to reference
895  * lambdas that capture by reference.
896  */
897
898 template <typename FunctionType>
899 class FunctionRef;
900
901 template <typename ReturnType, typename... Args>
902 class FunctionRef<ReturnType(Args...)> final {
903   using Call = ReturnType (*)(void*, Args&&...);
904
905   static ReturnType uninitCall(void*, Args&&...) {
906     throw std::bad_function_call();
907   }
908
909   template <typename Fun>
910   static ReturnType call(void* object, Args&&... args) {
911     using Pointer = _t<std::add_pointer<Fun>>;
912     return static_cast<ReturnType>(invoke(
913         static_cast<Fun&&>(*static_cast<Pointer>(object)),
914         static_cast<Args&&>(args)...));
915   }
916
917   void* object_{nullptr};
918   Call call_{&FunctionRef::uninitCall};
919
920  public:
921   /**
922    * Default constructor. Constructs an empty FunctionRef.
923    *
924    * Invoking it will throw std::bad_function_call.
925    */
926   FunctionRef() = default;
927
928   /**
929    * Construct a FunctionRef from a reference to a callable object.
930    */
931   template <
932       typename Fun,
933       typename std::enable_if<
934           Conjunction<
935               Negation<std::is_same<FunctionRef, _t<std::decay<Fun>>>>,
936               detail::function::IsCallableAs<Fun, ReturnType(Args...)>>::value,
937           int>::type = 0>
938   constexpr /* implicit */ FunctionRef(Fun&& fun) noexcept
939       // `Fun` may be a const type, in which case we have to do a const_cast
940       // to store the address in a `void*`. This is safe because the `void*`
941       // will be cast back to `Fun*` (which is a const pointer whenever `Fun`
942       // is a const type) inside `FunctionRef::call`
943       : object_(
944             const_cast<void*>(static_cast<void const*>(std::addressof(fun)))),
945         call_(&FunctionRef::call<Fun>) {}
946
947   ReturnType operator()(Args... args) const {
948     return call_(object_, static_cast<Args&&>(args)...);
949   }
950
951   constexpr explicit operator bool() const {
952     return object_;
953   }
954 };
955
956 } // namespace folly