Move folly/Bits.h to folly/lang/
[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 F, typename... Args>
288 using CallableResult = decltype(std::declval<F>()(std::declval<Args>()...));
289
290 template <
291     typename From,
292     typename To,
293     typename = typename std::enable_if<
294         !std::is_reference<To>::value || std::is_reference<From>::value>::type>
295 using SafeResultOf = decltype(static_cast<To>(std::declval<From>()));
296
297 template <typename FunctionType>
298 struct FunctionTraits;
299
300 template <typename ReturnType, typename... Args>
301 struct FunctionTraits<ReturnType(Args...)> {
302   using Call = ReturnType (*)(Data&, Args&&...);
303   using IsConst = std::false_type;
304   using ConstSignature = ReturnType(Args...) const;
305   using NonConstSignature = ReturnType(Args...);
306   using OtherSignature = ConstSignature;
307
308   template <typename F>
309   using ResultOf =
310       SafeResultOf<CallableResult<_t<std::decay<F>>&, Args...>, ReturnType>;
311
312   template <typename Fun>
313   static ReturnType callSmall(Data& p, Args&&... args) {
314     return static_cast<ReturnType>((*static_cast<Fun*>(
315         static_cast<void*>(&p.tiny)))(static_cast<Args&&>(args)...));
316   }
317
318   template <typename Fun>
319   static ReturnType callBig(Data& p, Args&&... args) {
320     return static_cast<ReturnType>(
321         (*static_cast<Fun*>(p.big))(static_cast<Args&&>(args)...));
322   }
323
324   static ReturnType uninitCall(Data&, Args&&...) {
325     throw std::bad_function_call();
326   }
327
328   ReturnType operator()(Args... args) {
329     auto& fn = *static_cast<Function<NonConstSignature>*>(this);
330     return fn.call_(fn.data_, static_cast<Args&&>(args)...);
331   }
332
333   class SharedProxy {
334     std::shared_ptr<Function<NonConstSignature>> sp_;
335
336    public:
337     explicit SharedProxy(Function<NonConstSignature>&& func)
338         : sp_(std::make_shared<Function<NonConstSignature>>(std::move(func))) {}
339     ReturnType operator()(Args&&... args) const {
340       return (*sp_)(static_cast<Args&&>(args)...);
341     }
342   };
343 };
344
345 template <typename ReturnType, typename... Args>
346 struct FunctionTraits<ReturnType(Args...) const> {
347   using Call = ReturnType (*)(Data&, Args&&...);
348   using IsConst = std::true_type;
349   using ConstSignature = ReturnType(Args...) const;
350   using NonConstSignature = ReturnType(Args...);
351   using OtherSignature = NonConstSignature;
352
353   template <typename F>
354   using ResultOf = SafeResultOf<
355       CallableResult<const _t<std::decay<F>>&, Args...>,
356       ReturnType>;
357
358   template <typename Fun>
359   static ReturnType callSmall(Data& p, Args&&... args) {
360     return static_cast<ReturnType>((*static_cast<const Fun*>(
361         static_cast<void*>(&p.tiny)))(static_cast<Args&&>(args)...));
362   }
363
364   template <typename Fun>
365   static ReturnType callBig(Data& p, Args&&... args) {
366     return static_cast<ReturnType>(
367         (*static_cast<const Fun*>(p.big))(static_cast<Args&&>(args)...));
368   }
369
370   static ReturnType uninitCall(Data&, Args&&...) {
371     throw std::bad_function_call();
372   }
373
374   ReturnType operator()(Args... args) const {
375     auto& fn = *static_cast<const Function<ConstSignature>*>(this);
376     return fn.call_(fn.data_, static_cast<Args&&>(args)...);
377   }
378
379   class SharedProxy {
380     std::shared_ptr<Function<ConstSignature>> sp_;
381
382    public:
383     explicit SharedProxy(Function<ConstSignature>&& func)
384         : sp_(std::make_shared<Function<ConstSignature>>(std::move(func))) {}
385     ReturnType operator()(Args&&... args) const {
386       return (*sp_)(static_cast<Args&&>(args)...);
387     }
388   };
389 };
390
391 #if FOLLY_HAVE_NOEXCEPT_FUNCTION_TYPE
392 template <typename ReturnType, typename... Args>
393 struct FunctionTraits<ReturnType(Args...) noexcept> {
394   using Call = ReturnType (*)(Data&, Args&&...) noexcept;
395   using IsConst = std::false_type;
396   using ConstSignature = ReturnType(Args...) const noexcept;
397   using NonConstSignature = ReturnType(Args...) noexcept;
398   using OtherSignature = ConstSignature;
399
400   template <typename F>
401   using ResultOf =
402       SafeResultOf<CallableResult<_t<std::decay<F>>&, Args...>, ReturnType>;
403
404   template <typename Fun>
405   static ReturnType callSmall(Data& p, Args&&... args) noexcept {
406     return static_cast<ReturnType>((*static_cast<Fun*>(
407         static_cast<void*>(&p.tiny)))(static_cast<Args&&>(args)...));
408   }
409
410   template <typename Fun>
411   static ReturnType callBig(Data& p, Args&&... args) noexcept {
412     return static_cast<ReturnType>(
413         (*static_cast<Fun*>(p.big))(static_cast<Args&&>(args)...));
414   }
415
416   static ReturnType uninitCall(Data&, Args&&...) noexcept {
417     throw std::bad_function_call();
418   }
419
420   ReturnType operator()(Args... args) noexcept {
421     auto& fn = *static_cast<Function<NonConstSignature>*>(this);
422     return fn.call_(fn.data_, static_cast<Args&&>(args)...);
423   }
424
425   class SharedProxy {
426     std::shared_ptr<Function<NonConstSignature>> sp_;
427
428    public:
429     explicit SharedProxy(Function<NonConstSignature>&& func)
430         : sp_(std::make_shared<Function<NonConstSignature>>(std::move(func))) {}
431     ReturnType operator()(Args&&... args) const {
432       return (*sp_)(static_cast<Args&&>(args)...);
433     }
434   };
435 };
436
437 template <typename ReturnType, typename... Args>
438 struct FunctionTraits<ReturnType(Args...) const noexcept> {
439   using Call = ReturnType (*)(Data&, Args&&...) noexcept;
440   using IsConst = std::true_type;
441   using ConstSignature = ReturnType(Args...) const noexcept;
442   using NonConstSignature = ReturnType(Args...) noexcept;
443   using OtherSignature = NonConstSignature;
444
445   template <typename F>
446   using ResultOf = SafeResultOf<
447       CallableResult<const _t<std::decay<F>>&, Args...>,
448       ReturnType>;
449
450   template <typename Fun>
451   static ReturnType callSmall(Data& p, Args&&... args) noexcept {
452     return static_cast<ReturnType>((*static_cast<const Fun*>(
453         static_cast<void*>(&p.tiny)))(static_cast<Args&&>(args)...));
454   }
455
456   template <typename Fun>
457   static ReturnType callBig(Data& p, Args&&... args) noexcept {
458     return static_cast<ReturnType>(
459         (*static_cast<const Fun*>(p.big))(static_cast<Args&&>(args)...));
460   }
461
462   static ReturnType uninitCall(Data&, Args&&...) noexcept {
463     throw std::bad_function_call();
464   }
465
466   ReturnType operator()(Args... args) const noexcept {
467     auto& fn = *static_cast<const Function<ConstSignature>*>(this);
468     return fn.call_(fn.data_, static_cast<Args&&>(args)...);
469   }
470
471   class SharedProxy {
472     std::shared_ptr<Function<ConstSignature>> sp_;
473
474    public:
475     explicit SharedProxy(Function<ConstSignature>&& func)
476         : sp_(std::make_shared<Function<ConstSignature>>(std::move(func))) {}
477     ReturnType operator()(Args&&... args) const {
478       return (*sp_)(static_cast<Args&&>(args)...);
479     }
480   };
481 };
482 #endif
483
484 template <typename Fun>
485 bool execSmall(Op o, Data* src, Data* dst) {
486   switch (o) {
487     case Op::MOVE:
488       ::new (static_cast<void*>(&dst->tiny))
489           Fun(std::move(*static_cast<Fun*>(static_cast<void*>(&src->tiny))));
490       FOLLY_FALLTHROUGH;
491     case Op::NUKE:
492       static_cast<Fun*>(static_cast<void*>(&src->tiny))->~Fun();
493       break;
494     case Op::FULL:
495       return true;
496     case Op::HEAP:
497       break;
498   }
499   return false;
500 }
501
502 template <typename Fun>
503 bool execBig(Op o, Data* src, Data* dst) {
504   switch (o) {
505     case Op::MOVE:
506       dst->big = src->big;
507       src->big = nullptr;
508       break;
509     case Op::NUKE:
510       delete static_cast<Fun*>(src->big);
511       break;
512     case Op::FULL:
513     case Op::HEAP:
514       break;
515   }
516   return true;
517 }
518
519 } // namespace function
520 } // namespace detail
521
522 template <typename FunctionType>
523 class Function final : private detail::function::FunctionTraits<FunctionType> {
524   // These utility types are defined outside of the template to reduce
525   // the number of instantiations, and then imported in the class
526   // namespace for convenience.
527   using Data = detail::function::Data;
528   using Op = detail::function::Op;
529   using SmallTag = detail::function::SmallTag;
530   using HeapTag = detail::function::HeapTag;
531   using CoerceTag = detail::function::CoerceTag;
532
533   using Traits = detail::function::FunctionTraits<FunctionType>;
534   using Call = typename Traits::Call;
535   using Exec = bool (*)(Op, Data*, Data*);
536
537   template <typename Fun>
538   using IsSmall = detail::function::IsSmall<Fun>;
539
540   // The `data_` member is mutable to allow `constCastFunction` to work without
541   // invoking undefined behavior. Const-correctness is only violated when
542   // `FunctionType` is a const function type (e.g., `int() const`) and `*this`
543   // is the result of calling `constCastFunction`.
544   mutable Data data_{};
545   Call call_{&Traits::uninitCall};
546   Exec exec_{&detail::function::uninitNoop};
547
548   friend Traits;
549   friend Function<typename Traits::ConstSignature> folly::constCastFunction<>(
550       Function<typename Traits::NonConstSignature>&&) noexcept;
551   friend class Function<typename Traits::OtherSignature>;
552
553   template <typename Fun>
554   Function(Fun&& fun, SmallTag) noexcept {
555     using FunT = typename std::decay<Fun>::type;
556     if (!detail::function::isNullPtrFn(fun)) {
557       ::new (static_cast<void*>(&data_.tiny)) FunT(static_cast<Fun&&>(fun));
558       call_ = &Traits::template callSmall<FunT>;
559       exec_ = &detail::function::execSmall<FunT>;
560     }
561   }
562
563   template <typename Fun>
564   Function(Fun&& fun, HeapTag) {
565     using FunT = typename std::decay<Fun>::type;
566     data_.big = new FunT(static_cast<Fun&&>(fun));
567     call_ = &Traits::template callBig<FunT>;
568     exec_ = &detail::function::execBig<FunT>;
569   }
570
571   template <typename Signature>
572   Function(Function<Signature>&& that, CoerceTag)
573       : Function(static_cast<Function<Signature>&&>(that), HeapTag{}) {}
574
575   Function(
576       Function<typename Traits::OtherSignature>&& that,
577       CoerceTag) noexcept {
578     that.exec_(Op::MOVE, &that.data_, &data_);
579     std::swap(call_, that.call_);
580     std::swap(exec_, that.exec_);
581   }
582
583  public:
584   /**
585    * Default constructor. Constructs an empty Function.
586    */
587   Function() = default;
588
589   // not copyable
590   Function(const Function&) = delete;
591
592 #if __OBJC__
593   // Make sure Objective C blocks are copied
594   template <class ReturnType, class... Args>
595   /*implicit*/ Function(ReturnType (^objCBlock)(Args... args))
596       : Function([blockCopy = (ReturnType (^)(Args...))[objCBlock copy]](
597                      Args... args) { return blockCopy(args...); }){};
598 #endif
599
600   /**
601    * Move constructor
602    */
603   Function(Function&& that) noexcept {
604     that.exec_(Op::MOVE, &that.data_, &data_);
605     std::swap(call_, that.call_);
606     std::swap(exec_, that.exec_);
607   }
608
609   /**
610    * Constructs an empty `Function`.
611    */
612   /* implicit */ Function(std::nullptr_t) noexcept {}
613
614   /**
615    * Constructs a new `Function` from any callable object that is _not_ a
616    * `folly::Function`. This handles function pointers, pointers to static
617    * member functions, `std::reference_wrapper` objects, `std::function`
618    * objects, and arbitrary objects that implement `operator()` if the parameter
619    * signature matches (i.e. it returns an object convertible to `R` when called
620    * with `Args...`).
621    *
622    * \note `typename Traits::template ResultOf<Fun>` prevents this overload
623    * from being selected by overload resolution when `fun` is not a compatible
624    * function.
625    *
626    * \note The noexcept requires some explanation. `IsSmall` is true when the
627    * decayed type fits within the internal buffer and is noexcept-movable. But
628    * this ctor might copy, not move. What we need here, if this ctor does a
629    * copy, is that this ctor be noexcept when the copy is noexcept. That is not
630    * checked in `IsSmall`, and shouldn't be, because once the `Function` is
631    * constructed, the contained object is never copied. This check is for this
632    * ctor only, in the case that this ctor does a copy.
633    */
634   template <
635       typename Fun,
636       typename = detail::function::EnableIfNotFunction<Fun>,
637       typename = typename Traits::template ResultOf<Fun>>
638   /* implicit */ Function(Fun fun) noexcept(
639       IsSmall<Fun>::value && noexcept(Fun(std::declval<Fun>())))
640       : Function(std::move(fun), IsSmall<Fun>{}) {}
641
642   /**
643    * For move-constructing from a `folly::Function<X(Ys...) [const?]>`.
644    * For a `Function` with a `const` function type, the object must be
645    * callable from a `const`-reference, i.e. implement `operator() const`.
646    * For a `Function` with a non-`const` function type, the object will
647    * be called from a non-const reference, which means that it will execute
648    * a non-const `operator()` if it is defined, and falls back to
649    * `operator() const` otherwise.
650    */
651   template <
652       typename Signature,
653       typename = typename Traits::template ResultOf<Function<Signature>>>
654   Function(Function<Signature>&& that) noexcept(
655       noexcept(Function(std::move(that), CoerceTag{})))
656       : Function(std::move(that), CoerceTag{}) {}
657
658   /**
659    * If `ptr` is null, constructs an empty `Function`. Otherwise,
660    * this constructor is equivalent to `Function(std::mem_fn(ptr))`.
661    */
662   template <
663       typename Member,
664       typename Class,
665       // Prevent this overload from being selected when `ptr` is not a
666       // compatible member function pointer.
667       typename = decltype(Function(std::mem_fn((Member Class::*)0)))>
668   /* implicit */ Function(Member Class::*ptr) noexcept {
669     if (ptr) {
670       *this = std::mem_fn(ptr);
671     }
672   }
673
674   ~Function() {
675     exec_(Op::NUKE, &data_, nullptr);
676   }
677
678   Function& operator=(const Function&) = delete;
679
680 #if __OBJC__
681   // Make sure Objective C blocks are copied
682   template <class ReturnType, class... Args>
683   /* implicit */ Function &operator=(ReturnType (^objCBlock)(Args... args)) {
684     (*this) = [blockCopy = (ReturnType (^)(Args...))[objCBlock copy]](
685                   Args... args) { return blockCopy(args...); };
686     return *this;
687   }
688 #endif
689
690   /**
691    * Move assignment operator
692    *
693    * \note Leaves `that` in a valid but unspecified state. If `&that == this`
694    * then `*this` is left in a valid but unspecified state.
695    */
696   Function& operator=(Function&& that) noexcept {
697     // Q: Why is it safe to destroy and reconstruct this object in place?
698     // A: Two reasons: First, `Function` is a final class, so in doing this
699     //    we aren't slicing off any derived parts. And second, the move
700     //    operation is guaranteed not to throw so we always leave the object
701     //    in a valid state.
702     // In the case of self-move (this == &that), this leaves the object in
703     // a default-constructed state. First the object is destroyed, then we
704     // pass the destroyed object to the move constructor. The first thing the
705     // move constructor does is default-construct the object. That object is
706     // "moved" into itself, which is a no-op for a default-constructed Function.
707     this->~Function();
708     ::new (this) Function(std::move(that));
709     return *this;
710   }
711
712   /**
713    * Assigns a callable object to this `Function`. If the operation fails,
714    * `*this` is left unmodified.
715    *
716    * \note `typename = decltype(Function(std::declval<Fun>()))` prevents this
717    * overload from being selected by overload resolution when `fun` is not a
718    * compatible function.
719    */
720   template <typename Fun, typename = decltype(Function(std::declval<Fun>()))>
721   Function& operator=(Fun fun) noexcept(
722       noexcept(/* implicit */ Function(std::declval<Fun>()))) {
723     // Doing this in place is more efficient when we can do so safely.
724     if (noexcept(/* implicit */ Function(std::declval<Fun>()))) {
725       // Q: Why is is safe to destroy and reconstruct this object in place?
726       // A: See the explanation in the move assignment operator.
727       this->~Function();
728       ::new (this) Function(std::move(fun));
729     } else {
730       // Construct a temporary and (nothrow) swap.
731       Function(std::move(fun)).swap(*this);
732     }
733     return *this;
734   }
735
736   /**
737    * For assigning from a `Function<X(Ys..) [const?]>`.
738    */
739   template <
740       typename Signature,
741       typename = typename Traits::template ResultOf<Function<Signature>>>
742   Function& operator=(Function<Signature>&& that) noexcept(
743       noexcept(Function(std::move(that)))) {
744     return (*this = Function(std::move(that)));
745   }
746
747   /**
748    * Clears this `Function`.
749    */
750   Function& operator=(std::nullptr_t) noexcept {
751     return (*this = Function());
752   }
753
754   /**
755    * If `ptr` is null, clears this `Function`. Otherwise, this assignment
756    * operator is equivalent to `*this = std::mem_fn(ptr)`.
757    */
758   template <typename Member, typename Class>
759   auto operator=(Member Class::*ptr) noexcept
760       // Prevent this overload from being selected when `ptr` is not a
761       // compatible member function pointer.
762       -> decltype(operator=(std::mem_fn(ptr))) {
763     return ptr ? (*this = std::mem_fn(ptr)) : (*this = Function());
764   }
765
766   /**
767    * Call the wrapped callable object with the specified arguments.
768    */
769   using Traits::operator();
770
771   /**
772    * Exchanges the callable objects of `*this` and `that`.
773    */
774   void swap(Function& that) noexcept {
775     std::swap(*this, that);
776   }
777
778   /**
779    * Returns `true` if this `Function` contains a callable, i.e. is
780    * non-empty.
781    */
782   explicit operator bool() const noexcept {
783     return exec_(Op::FULL, nullptr, nullptr);
784   }
785
786   /**
787    * Returns `true` if this `Function` stores the callable on the
788    * heap. If `false` is returned, there has been no additional memory
789    * allocation and the callable is stored inside the `Function`
790    * object itself.
791    */
792   bool hasAllocatedMemory() const noexcept {
793     return exec_(Op::HEAP, nullptr, nullptr);
794   }
795
796   using typename Traits::SharedProxy;
797
798   /**
799    * Move this `Function` into a copyable callable object, of which all copies
800    * share the state.
801    */
802   SharedProxy asSharedProxy() && {
803     return SharedProxy{std::move(*this)};
804   }
805
806   /**
807    * Construct a `std::function` by moving in the contents of this `Function`.
808    * Note that the returned `std::function` will share its state (i.e. captured
809    * data) across all copies you make of it, so be very careful when copying.
810    */
811   std::function<typename Traits::NonConstSignature> asStdFunction() && {
812     return std::move(*this).asSharedProxy();
813   }
814 };
815
816 template <typename FunctionType>
817 void swap(Function<FunctionType>& lhs, Function<FunctionType>& rhs) noexcept {
818   lhs.swap(rhs);
819 }
820
821 template <typename FunctionType>
822 bool operator==(const Function<FunctionType>& fn, std::nullptr_t) {
823   return !fn;
824 }
825
826 template <typename FunctionType>
827 bool operator==(std::nullptr_t, const Function<FunctionType>& fn) {
828   return !fn;
829 }
830
831 template <typename FunctionType>
832 bool operator!=(const Function<FunctionType>& fn, std::nullptr_t) {
833   return !(fn == nullptr);
834 }
835
836 template <typename FunctionType>
837 bool operator!=(std::nullptr_t, const Function<FunctionType>& fn) {
838   return !(nullptr == fn);
839 }
840
841 /**
842  * NOTE: See detailed note about `constCastFunction` at the top of the file.
843  * This is potentially dangerous and requires the equivalent of a `const_cast`.
844  */
845 template <typename ReturnType, typename... Args>
846 Function<ReturnType(Args...) const> constCastFunction(
847     Function<ReturnType(Args...)>&& that) noexcept {
848   return Function<ReturnType(Args...) const>{std::move(that),
849                                              detail::function::CoerceTag{}};
850 }
851
852 template <typename ReturnType, typename... Args>
853 Function<ReturnType(Args...) const> constCastFunction(
854     Function<ReturnType(Args...) const>&& that) noexcept {
855   return std::move(that);
856 }
857
858 #if FOLLY_HAVE_NOEXCEPT_FUNCTION_TYPE
859 template <typename ReturnType, typename... Args>
860 Function<ReturnType(Args...) const noexcept> constCastFunction(
861     Function<ReturnType(Args...) noexcept>&& that) noexcept {
862   return Function<ReturnType(Args...) const noexcept>{
863       std::move(that), detail::function::CoerceTag{}};
864 }
865
866 template <typename ReturnType, typename... Args>
867 Function<ReturnType(Args...) const noexcept> constCastFunction(
868     Function<ReturnType(Args...) const noexcept>&& that) noexcept {
869   return std::move(that);
870 }
871 #endif
872
873 namespace detail {
874 namespace function {
875 template <typename Fun, typename FunctionType, typename = void>
876 struct IsCallableAsImpl : std::false_type {};
877
878 template <typename Fun, typename ReturnType, typename... Args>
879 struct IsCallableAsImpl<
880     Fun,
881     ReturnType(Args...),
882     void_t<typename std::result_of<Fun && (Args && ...)>::type>>
883     : std::is_convertible<
884           typename std::result_of<Fun && (Args && ...)>::type,
885           ReturnType> {};
886
887 template <typename Fun, typename FunctionType>
888 struct IsCallableAs : IsCallableAsImpl<Fun, FunctionType> {};
889 } // namespace function
890 } // namespace detail
891
892 /**
893  * @class FunctionRef
894  *
895  * @brief A reference wrapper for callable objects
896  *
897  * FunctionRef is similar to std::reference_wrapper, but the template parameter
898  * is the function signature type rather than the type of the referenced object.
899  * A folly::FunctionRef is cheap to construct as it contains only a pointer to
900  * the referenced callable and a pointer to a function which invokes the
901  * callable.
902  *
903  * The user of FunctionRef must be aware of the reference semantics: storing a
904  * copy of a FunctionRef is potentially dangerous and should be avoided unless
905  * the referenced object definitely outlives the FunctionRef object. Thus any
906  * function that accepts a FunctionRef parameter should only use it to invoke
907  * the referenced function and not store a copy of it. Knowing that FunctionRef
908  * itself has reference semantics, it is generally okay to use it to reference
909  * lambdas that capture by reference.
910  */
911
912 template <typename FunctionType>
913 class FunctionRef;
914
915 template <typename ReturnType, typename... Args>
916 class FunctionRef<ReturnType(Args...)> final {
917   using Call = ReturnType (*)(void*, Args&&...);
918
919   static ReturnType uninitCall(void*, Args&&...) {
920     throw std::bad_function_call();
921   }
922
923   template <typename Fun>
924   static ReturnType call(void* object, Args&&... args) {
925     using Pointer = _t<std::add_pointer<Fun>>;
926     return static_cast<ReturnType>(invoke(
927         static_cast<Fun&&>(*static_cast<Pointer>(object)),
928         static_cast<Args&&>(args)...));
929   }
930
931   void* object_{nullptr};
932   Call call_{&FunctionRef::uninitCall};
933
934  public:
935   /**
936    * Default constructor. Constructs an empty FunctionRef.
937    *
938    * Invoking it will throw std::bad_function_call.
939    */
940   FunctionRef() = default;
941
942   /**
943    * Construct a FunctionRef from a reference to a callable object.
944    */
945   template <
946       typename Fun,
947       typename std::enable_if<
948           Conjunction<
949               Negation<std::is_same<FunctionRef, _t<std::decay<Fun>>>>,
950               detail::function::IsCallableAs<Fun, ReturnType(Args...)>>::value,
951           int>::type = 0>
952   constexpr /* implicit */ FunctionRef(Fun&& fun) noexcept
953       // `Fun` may be a const type, in which case we have to do a const_cast
954       // to store the address in a `void*`. This is safe because the `void*`
955       // will be cast back to `Fun*` (which is a const pointer whenever `Fun`
956       // is a const type) inside `FunctionRef::call`
957       : object_(
958             const_cast<void*>(static_cast<void const*>(std::addressof(fun)))),
959         call_(&FunctionRef::call<Fun>) {}
960
961   ReturnType operator()(Args... args) const {
962     return call_(object_, static_cast<Args&&>(args)...);
963   }
964
965   constexpr explicit operator bool() const {
966     return object_;
967   }
968 };
969
970 } // namespace folly