callback.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. //
  5. // NOTE: Header files that do not require the full definition of
  6. // base::{Once,Repeating}Callback or base::{Once,Repeating}Closure should
  7. // #include "base/callback_forward.h" instead of this file.
  8. #ifndef BASE_CALLBACK_H_
  9. #define BASE_CALLBACK_H_
  10. #include <stddef.h>
  11. #include <utility>
  12. #include "base/bind.h"
  13. #include "base/callback_forward.h" // IWYU pragma: export
  14. #include "base/callback_internal.h"
  15. #include "base/check.h"
  16. #include "base/functional/function_ref.h"
  17. #include "base/notreached.h"
  18. #include "base/types/always_false.h"
  19. // -----------------------------------------------------------------------------
  20. // Usage documentation
  21. // -----------------------------------------------------------------------------
  22. //
  23. // Overview:
  24. // A callback is similar in concept to a function pointer: it wraps a runnable
  25. // object such as a function, method, lambda, or even another callback, allowing
  26. // the runnable object to be invoked later via the callback object.
  27. //
  28. // Unlike function pointers, callbacks are created with base::BindOnce() or
  29. // base::BindRepeating() and support partial function application.
  30. //
  31. // A base::OnceCallback may be Run() at most once; a base::RepeatingCallback may
  32. // be Run() any number of times. |is_null()| is guaranteed to return true for a
  33. // moved-from callback.
  34. //
  35. // // The lambda takes two arguments, but the first argument |x| is bound at
  36. // // callback creation.
  37. // base::OnceCallback<int(int)> cb = base::BindOnce([] (int x, int y) {
  38. // return x + y;
  39. // }, 1);
  40. // // Run() only needs the remaining unbound argument |y|.
  41. // printf("1 + 2 = %d\n", std::move(cb).Run(2)); // Prints 3
  42. // printf("cb is null? %s\n",
  43. // cb.is_null() ? "true" : "false"); // Prints true
  44. // std::move(cb).Run(2); // Crashes since |cb| has already run.
  45. //
  46. // Callbacks also support cancellation. A common use is binding the receiver
  47. // object as a WeakPtr<T>. If that weak pointer is invalidated, calling Run()
  48. // will be a no-op. Note that |IsCancelled()| and |is_null()| are distinct:
  49. // simply cancelling a callback will not also make it null.
  50. //
  51. // See //docs/callback.md for the full documentation.
  52. namespace base {
  53. namespace internal {
  54. struct NullCallbackTag {
  55. template <typename Signature>
  56. struct WithSignature {};
  57. };
  58. struct DoNothingCallbackTag {
  59. template <typename Signature>
  60. struct WithSignature {};
  61. };
  62. } // namespace internal
  63. template <typename R, typename... Args>
  64. class OnceCallback<R(Args...)> : public internal::CallbackBase {
  65. public:
  66. using ResultType = R;
  67. using RunType = R(Args...);
  68. using PolymorphicInvoke = R (*)(internal::BindStateBase*,
  69. internal::PassingType<Args>...);
  70. constexpr OnceCallback() = default;
  71. OnceCallback(std::nullptr_t) = delete;
  72. constexpr OnceCallback(internal::NullCallbackTag) : OnceCallback() {}
  73. constexpr OnceCallback& operator=(internal::NullCallbackTag) {
  74. *this = OnceCallback();
  75. return *this;
  76. }
  77. constexpr OnceCallback(internal::NullCallbackTag::WithSignature<RunType>)
  78. : OnceCallback(internal::NullCallbackTag()) {}
  79. constexpr OnceCallback& operator=(
  80. internal::NullCallbackTag::WithSignature<RunType>) {
  81. *this = internal::NullCallbackTag();
  82. return *this;
  83. }
  84. constexpr OnceCallback(internal::DoNothingCallbackTag)
  85. : OnceCallback(BindOnce([](Args... args) {})) {}
  86. constexpr OnceCallback& operator=(internal::DoNothingCallbackTag) {
  87. *this = BindOnce([](Args... args) {});
  88. return *this;
  89. }
  90. constexpr OnceCallback(internal::DoNothingCallbackTag::WithSignature<RunType>)
  91. : OnceCallback(internal::DoNothingCallbackTag()) {}
  92. constexpr OnceCallback& operator=(
  93. internal::DoNothingCallbackTag::WithSignature<RunType>) {
  94. *this = internal::DoNothingCallbackTag();
  95. return *this;
  96. }
  97. explicit OnceCallback(internal::BindStateBase* bind_state)
  98. : internal::CallbackBase(bind_state) {}
  99. OnceCallback(const OnceCallback&) = delete;
  100. OnceCallback& operator=(const OnceCallback&) = delete;
  101. OnceCallback(OnceCallback&&) noexcept = default;
  102. OnceCallback& operator=(OnceCallback&&) noexcept = default;
  103. OnceCallback(RepeatingCallback<RunType> other)
  104. : internal::CallbackBase(std::move(other)) {}
  105. OnceCallback& operator=(RepeatingCallback<RunType> other) {
  106. static_cast<internal::CallbackBase&>(*this) = std::move(other);
  107. return *this;
  108. }
  109. R Run(Args... args) const & {
  110. static_assert(!sizeof(*this),
  111. "OnceCallback::Run() may only be invoked on a non-const "
  112. "rvalue, i.e. std::move(callback).Run().");
  113. NOTREACHED();
  114. }
  115. R Run(Args... args) && {
  116. // Move the callback instance into a local variable before the invocation,
  117. // that ensures the internal state is cleared after the invocation.
  118. // It's not safe to touch |this| after the invocation, since running the
  119. // bound function may destroy |this|.
  120. OnceCallback cb = std::move(*this);
  121. PolymorphicInvoke f =
  122. reinterpret_cast<PolymorphicInvoke>(cb.polymorphic_invoke());
  123. return f(cb.bind_state_.get(), std::forward<Args>(args)...);
  124. }
  125. // Then() returns a new OnceCallback that receives the same arguments as
  126. // |this|, and with the return type of |then|. The returned callback will:
  127. // 1) Run the functor currently bound to |this| callback.
  128. // 2) Run the |then| callback with the result from step 1 as its single
  129. // argument.
  130. // 3) Return the value from running the |then| callback.
  131. //
  132. // Since this method generates a callback that is a replacement for `this`,
  133. // `this` will be consumed and reset to a null callback to ensure the
  134. // originally-bound functor can be run at most once.
  135. template <typename ThenR, typename... ThenArgs>
  136. OnceCallback<ThenR(Args...)> Then(OnceCallback<ThenR(ThenArgs...)> then) && {
  137. CHECK(then);
  138. return BindOnce(
  139. internal::ThenHelper<
  140. OnceCallback, OnceCallback<ThenR(ThenArgs...)>>::CreateTrampoline(),
  141. std::move(*this), std::move(then));
  142. }
  143. // This overload is required; even though RepeatingCallback is implicitly
  144. // convertible to OnceCallback, that conversion will not used when matching
  145. // for template argument deduction.
  146. template <typename ThenR, typename... ThenArgs>
  147. OnceCallback<ThenR(Args...)> Then(
  148. RepeatingCallback<ThenR(ThenArgs...)> then) && {
  149. CHECK(then);
  150. return BindOnce(
  151. internal::ThenHelper<
  152. OnceCallback,
  153. RepeatingCallback<ThenR(ThenArgs...)>>::CreateTrampoline(),
  154. std::move(*this), std::move(then));
  155. }
  156. template <typename Signature>
  157. // NOLINTNEXTLINE(google-explicit-constructor)
  158. operator FunctionRef<Signature>() & {
  159. static_assert(
  160. AlwaysFalse<Signature>,
  161. "need to convert a base::OnceCallback to base::FunctionRef? "
  162. "Please bring up this use case on #cxx (Slack) or cxx@chromium.org.");
  163. }
  164. template <typename Signature>
  165. // NOLINTNEXTLINE(google-explicit-constructor)
  166. operator FunctionRef<Signature>() && {
  167. static_assert(
  168. AlwaysFalse<Signature>,
  169. "using base::BindOnce() is not necessary with base::FunctionRef; is it "
  170. "possible to use a capturing lambda directly? If not, please bring up "
  171. "this use case on #cxx (Slack) or cxx@chromium.org.");
  172. }
  173. };
  174. template <typename R, typename... Args>
  175. class RepeatingCallback<R(Args...)> : public internal::CallbackBaseCopyable {
  176. public:
  177. using ResultType = R;
  178. using RunType = R(Args...);
  179. using PolymorphicInvoke = R (*)(internal::BindStateBase*,
  180. internal::PassingType<Args>...);
  181. constexpr RepeatingCallback() = default;
  182. RepeatingCallback(std::nullptr_t) = delete;
  183. constexpr RepeatingCallback(internal::NullCallbackTag)
  184. : RepeatingCallback() {}
  185. constexpr RepeatingCallback& operator=(internal::NullCallbackTag) {
  186. *this = RepeatingCallback();
  187. return *this;
  188. }
  189. constexpr RepeatingCallback(internal::NullCallbackTag::WithSignature<RunType>)
  190. : RepeatingCallback(internal::NullCallbackTag()) {}
  191. constexpr RepeatingCallback& operator=(
  192. internal::NullCallbackTag::WithSignature<RunType>) {
  193. *this = internal::NullCallbackTag();
  194. return *this;
  195. }
  196. constexpr RepeatingCallback(internal::DoNothingCallbackTag)
  197. : RepeatingCallback(BindRepeating([](Args... args) {})) {}
  198. constexpr RepeatingCallback& operator=(internal::DoNothingCallbackTag) {
  199. *this = BindRepeating([](Args... args) {});
  200. return *this;
  201. }
  202. constexpr RepeatingCallback(
  203. internal::DoNothingCallbackTag::WithSignature<RunType>)
  204. : RepeatingCallback(internal::DoNothingCallbackTag()) {}
  205. constexpr RepeatingCallback& operator=(
  206. internal::DoNothingCallbackTag::WithSignature<RunType>) {
  207. *this = internal::DoNothingCallbackTag();
  208. return *this;
  209. }
  210. explicit RepeatingCallback(internal::BindStateBase* bind_state)
  211. : internal::CallbackBaseCopyable(bind_state) {}
  212. // Copyable and movable.
  213. RepeatingCallback(const RepeatingCallback&) = default;
  214. RepeatingCallback& operator=(const RepeatingCallback&) = default;
  215. RepeatingCallback(RepeatingCallback&&) noexcept = default;
  216. RepeatingCallback& operator=(RepeatingCallback&&) noexcept = default;
  217. bool operator==(const RepeatingCallback& other) const {
  218. return EqualsInternal(other);
  219. }
  220. bool operator!=(const RepeatingCallback& other) const {
  221. return !operator==(other);
  222. }
  223. R Run(Args... args) const & {
  224. PolymorphicInvoke f =
  225. reinterpret_cast<PolymorphicInvoke>(this->polymorphic_invoke());
  226. return f(this->bind_state_.get(), std::forward<Args>(args)...);
  227. }
  228. R Run(Args... args) && {
  229. // Move the callback instance into a local variable before the invocation,
  230. // that ensures the internal state is cleared after the invocation.
  231. // It's not safe to touch |this| after the invocation, since running the
  232. // bound function may destroy |this|.
  233. RepeatingCallback cb = std::move(*this);
  234. PolymorphicInvoke f =
  235. reinterpret_cast<PolymorphicInvoke>(cb.polymorphic_invoke());
  236. return f(std::move(cb).bind_state_.get(), std::forward<Args>(args)...);
  237. }
  238. // Then() returns a new RepeatingCallback that receives the same arguments as
  239. // |this|, and with the return type of |then|. The
  240. // returned callback will:
  241. // 1) Run the functor currently bound to |this| callback.
  242. // 2) Run the |then| callback with the result from step 1 as its single
  243. // argument.
  244. // 3) Return the value from running the |then| callback.
  245. //
  246. // If called on an rvalue (e.g. std::move(cb).Then(...)), this method
  247. // generates a callback that is a replacement for `this`. Therefore, `this`
  248. // will be consumed and reset to a null callback to ensure the
  249. // originally-bound functor will be run at most once.
  250. template <typename ThenR, typename... ThenArgs>
  251. RepeatingCallback<ThenR(Args...)> Then(
  252. RepeatingCallback<ThenR(ThenArgs...)> then) const& {
  253. CHECK(then);
  254. return BindRepeating(
  255. internal::ThenHelper<
  256. RepeatingCallback,
  257. RepeatingCallback<ThenR(ThenArgs...)>>::CreateTrampoline(),
  258. *this, std::move(then));
  259. }
  260. template <typename ThenR, typename... ThenArgs>
  261. RepeatingCallback<ThenR(Args...)> Then(
  262. RepeatingCallback<ThenR(ThenArgs...)> then) && {
  263. CHECK(then);
  264. return BindRepeating(
  265. internal::ThenHelper<
  266. RepeatingCallback,
  267. RepeatingCallback<ThenR(ThenArgs...)>>::CreateTrampoline(),
  268. std::move(*this), std::move(then));
  269. }
  270. template <typename Signature>
  271. // NOLINTNEXTLINE(google-explicit-constructor)
  272. operator FunctionRef<Signature>() & {
  273. static_assert(
  274. AlwaysFalse<Signature>,
  275. "need to convert a base::RepeatingCallback to base::FunctionRef? "
  276. "Please bring up this use case on #cxx (Slack) or cxx@chromium.org.");
  277. }
  278. template <typename Signature>
  279. // NOLINTNEXTLINE(google-explicit-constructor)
  280. operator FunctionRef<Signature>() && {
  281. static_assert(
  282. AlwaysFalse<Signature>,
  283. "using base::BindRepeating() is not necessary with base::FunctionRef; "
  284. "is it possible to use a capturing lambda directly? If not, please "
  285. "bring up this use case on #cxx (Slack) or cxx@chromium.org.");
  286. }
  287. };
  288. } // namespace base
  289. #endif // BASE_CALLBACK_H_