Function.h 33 KB

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