xref: /aosp_15_r20/external/cronet/base/functional/callback.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2012 The Chromium Authors
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/functional/callback_forward.h" instead of this file.
8 
9 #ifndef BASE_FUNCTIONAL_CALLBACK_H_
10 #define BASE_FUNCTIONAL_CALLBACK_H_
11 
12 #include <stddef.h>
13 
14 #include <type_traits>
15 #include <utility>
16 
17 #include "base/check.h"
18 #include "base/compiler_specific.h"
19 #include "base/functional/bind.h"
20 #include "base/functional/callback_forward.h"  // IWYU pragma: export
21 #include "base/functional/callback_internal.h"
22 #include "base/functional/callback_tags.h"
23 #include "base/functional/function_ref.h"
24 #include "base/notreached.h"
25 #include "base/types/always_false.h"
26 
27 // -----------------------------------------------------------------------------
28 // Usage documentation
29 // -----------------------------------------------------------------------------
30 //
31 // Overview:
32 // A callback is similar in concept to a function pointer: it wraps a runnable
33 // object such as a function, method, lambda, or even another callback, allowing
34 // the runnable object to be invoked later via the callback object.
35 //
36 // Unlike function pointers, callbacks are created with base::BindOnce() or
37 // base::BindRepeating() and support partial function application.
38 //
39 // A base::OnceCallback may be Run() at most once; a base::RepeatingCallback may
40 // be Run() any number of times. |is_null()| is guaranteed to return true for a
41 // moved-from callback.
42 //
43 //   // The lambda takes two arguments, but the first argument |x| is bound at
44 //   // callback creation.
45 //   base::OnceCallback<int(int)> cb = base::BindOnce([] (int x, int y) {
46 //     return x + y;
47 //   }, 1);
48 //   // Run() only needs the remaining unbound argument |y|.
49 //   printf("1 + 2 = %d\n", std::move(cb).Run(2));  // Prints 3
50 //   printf("cb is null? %s\n",
51 //          cb.is_null() ? "true" : "false");  // Prints true
52 //   std::move(cb).Run(2);  // Crashes since |cb| has already run.
53 //
54 // Callbacks also support cancellation. A common use is binding the receiver
55 // object as a WeakPtr<T>. If that weak pointer is invalidated, calling Run()
56 // will be a no-op. Note that |IsCancelled()| and |is_null()| are distinct:
57 // simply cancelling a callback will not also make it null.
58 //
59 // See //docs/callback.md for the full documentation.
60 
61 namespace base {
62 
63 namespace internal {
64 
65 template <bool is_once,
66           typename R,
67           typename... UnboundArgs,
68           typename... BoundArgs>
69 auto ToDoNothingCallback(
70     DoNothingCallbackTag::WithBoundArguments<BoundArgs...> t);
71 
72 }  // namespace internal
73 
74 template <typename R, typename... Args>
75 class TRIVIAL_ABI OnceCallback<R(Args...)> {
76  public:
77   using ResultType = R;
78   using RunType = R(Args...);
79   using PolymorphicInvoke = R (*)(internal::BindStateBase*,
80                                   internal::PassingType<Args>...);
81 
82   // Constructs a null `OnceCallback`. A null callback has no associated functor
83   // and cannot be run.
84   constexpr OnceCallback() = default;
85   // Disallowed to prevent ambiguity.
86   OnceCallback(std::nullptr_t) = delete;
87 
88   // `OnceCallback` is not copyable since its bound functor may only run at most
89   // once.
90   OnceCallback(const OnceCallback&) = delete;
91   OnceCallback& operator=(const OnceCallback&) = delete;
92 
93   // Subtle: since `this` is marked as TRIVIAL_ABI, the move operations
94   // must leave the moved-from callback in a trivially destructible state.
95   OnceCallback(OnceCallback&&) noexcept = default;
96   OnceCallback& operator=(OnceCallback&&) noexcept = default;
97 
98   ~OnceCallback() = default;
99 
100   // A `OnceCallback` is a strict subset of `RepeatingCallback`'s functionality,
101   // so allow seamless conversion.
102   // NOLINTNEXTLINE(google-explicit-constructor)
OnceCallback(RepeatingCallback<RunType> other)103   OnceCallback(RepeatingCallback<RunType> other)
104       : holder_(std::move(other.holder_)) {}
105   OnceCallback& operator=(RepeatingCallback<RunType> other) {
106     holder_ = std::move(other.holder_);
107     return *this;
108   }
109 
110   // Returns true if `this` is non-null and can be `Run()`.
111   explicit operator bool() const { return !!holder_; }
112   // Returns true if `this` is null and cannot be `Run()`.
is_null()113   bool is_null() const { return holder_.is_null(); }
114 
115   // Returns true if calling `Run()` is a no-op because of cancellation.
116   //
117   // - Not thread-safe, i.e. must be called on the same sequence that will
118   //   ultimately `Run()` the callback
119   // - May not be called on a null callback.
IsCancelled()120   bool IsCancelled() const { return holder_.IsCancelled(); }
121 
122   // Subtle version of `IsCancelled()` that allows cancellation state to be
123   // queried from any sequence. May return true even if the callback has
124   // actually been cancelled.
125   //
126   // Do not use. This is intended for internal //base usage.
127   // TODO(dcheng): Restrict this since it, in fact, being used outside of its
128   // originally intended use.
MaybeValid()129   bool MaybeValid() const { return holder_.MaybeValid(); }
130 
131   // Resets this to a null state.
Reset()132   REINITIALIZES_AFTER_MOVE void Reset() { holder_.Reset(); }
133 
134   // Non-consuming `Run()` is disallowed for `OnceCallback`.
Run(Args...args)135   R Run(Args... args) const& {
136     static_assert(!sizeof(*this),
137                   "OnceCallback::Run() may only be invoked on a non-const "
138                   "rvalue, i.e. std::move(callback).Run().");
139     NOTREACHED();
140   }
141 
142   // Calls the bound functor with any already-bound arguments + `args`. Consumes
143   // `this`, i.e. `this` becomes null.
144   //
145   // May not be called on a null callback.
Run(Args...args)146   R Run(Args... args) && {
147     CHECK(!holder_.is_null());
148 
149     // Move the callback instance into a local variable before the invocation,
150     // that ensures the internal state is cleared after the invocation.
151     // It's not safe to touch |this| after the invocation, since running the
152     // bound function may destroy |this|.
153     internal::BindStateHolder holder = std::move(holder_);
154     PolymorphicInvoke f =
155         reinterpret_cast<PolymorphicInvoke>(holder.polymorphic_invoke());
156     return f(holder.bind_state().get(), std::forward<Args>(args)...);
157   }
158 
159   // Then() returns a new OnceCallback that receives the same arguments as
160   // |this|, and with the return type of |then|. The returned callback will:
161   // 1) Run the functor currently bound to |this| callback.
162   // 2) Run the |then| callback with the result from step 1 as its single
163   //    argument.
164   // 3) Return the value from running the |then| callback.
165   //
166   // Since this method generates a callback that is a replacement for `this`,
167   // `this` will be consumed and reset to a null callback to ensure the
168   // originally-bound functor can be run at most once.
169   template <typename ThenR, typename... ThenArgs>
Then(OnceCallback<ThenR (ThenArgs...)> then)170   OnceCallback<ThenR(Args...)> Then(OnceCallback<ThenR(ThenArgs...)> then) && {
171     CHECK(then);
172     return base::BindOnce(
173         internal::ThenHelper<
174             OnceCallback, OnceCallback<ThenR(ThenArgs...)>>::CreateTrampoline(),
175         std::move(*this), std::move(then));
176   }
177 
178   // This overload is required; even though RepeatingCallback is implicitly
179   // convertible to OnceCallback, that conversion will not used when matching
180   // for template argument deduction.
181   template <typename ThenR, typename... ThenArgs>
Then(RepeatingCallback<ThenR (ThenArgs...)> then)182   OnceCallback<ThenR(Args...)> Then(
183       RepeatingCallback<ThenR(ThenArgs...)> then) && {
184     CHECK(then);
185     return base::BindOnce(
186         internal::ThenHelper<
187             OnceCallback,
188             RepeatingCallback<ThenR(ThenArgs...)>>::CreateTrampoline(),
189         std::move(*this), std::move(then));
190   }
191 
192   // Internal constructors for various callback helper tag types, e.g.
193   // `base::DoNothing()`.
194 
195   // NOLINTNEXTLINE(google-explicit-constructor)
OnceCallback(internal::NullCallbackTag)196   constexpr OnceCallback(internal::NullCallbackTag) : OnceCallback() {}
197   constexpr OnceCallback& operator=(internal::NullCallbackTag) {
198     *this = OnceCallback();
199     return *this;
200   }
201 
202   // NOLINTNEXTLINE(google-explicit-constructor)
OnceCallback(internal::NullCallbackTag::WithSignature<RunType>)203   constexpr OnceCallback(internal::NullCallbackTag::WithSignature<RunType>)
204       : OnceCallback(internal::NullCallbackTag()) {}
205   constexpr OnceCallback& operator=(
206       internal::NullCallbackTag::WithSignature<RunType>) {
207     *this = internal::NullCallbackTag();
208     return *this;
209   }
210 
211   // NOLINTNEXTLINE(google-explicit-constructor)
OnceCallback(internal::DoNothingCallbackTag)212   constexpr OnceCallback(internal::DoNothingCallbackTag)
213     requires(std::is_void_v<R>)
214       : OnceCallback(BindOnce([](Args... args) {})) {}
215   constexpr OnceCallback& operator=(internal::DoNothingCallbackTag)
requires(std::is_void_v<R>)216     requires(std::is_void_v<R>)
217   {
218     *this = BindOnce([](Args... args) {});
219     return *this;
220   }
221 
222   // NOLINTNEXTLINE(google-explicit-constructor)
OnceCallback(internal::DoNothingCallbackTag::WithSignature<RunType>)223   constexpr OnceCallback(internal::DoNothingCallbackTag::WithSignature<RunType>)
224     requires(std::is_void_v<R>)
225       : OnceCallback(internal::DoNothingCallbackTag()) {}
226   constexpr OnceCallback& operator=(
227       internal::DoNothingCallbackTag::WithSignature<RunType>)
requires(std::is_void_v<R>)228     requires(std::is_void_v<R>)
229   {
230     *this = internal::DoNothingCallbackTag();
231     return *this;
232   }
233 
234   template <typename... BoundArgs>
235   // NOLINTNEXTLINE(google-explicit-constructor)
OnceCallback(internal::DoNothingCallbackTag::WithBoundArguments<BoundArgs...> tag)236   constexpr OnceCallback(
237       internal::DoNothingCallbackTag::WithBoundArguments<BoundArgs...> tag)
238     requires(std::is_void_v<R>)
239       : OnceCallback(
240             internal::ToDoNothingCallback<true, R, Args...>(std::move(tag))) {}
241   template <typename... BoundArgs>
242   constexpr OnceCallback& operator=(
243       internal::DoNothingCallbackTag::WithBoundArguments<BoundArgs...> tag)
requires(std::is_void_v<R>)244     requires(std::is_void_v<R>)
245   {
246     *this = internal::ToDoNothingCallback<true, R, Args...>(std::move(tag));
247     return *this;
248   }
249 
250   // Internal constructor for `base::BindOnce()`.
OnceCallback(internal::BindStateBase * bind_state)251   explicit OnceCallback(internal::BindStateBase* bind_state)
252       : holder_(bind_state) {}
253 
254   template <typename Signature>
255   // NOLINTNEXTLINE(google-explicit-constructor)
256   operator FunctionRef<Signature>() & {
257     static_assert(
258         AlwaysFalse<Signature>,
259         "need to convert a base::OnceCallback to base::FunctionRef? "
260         "Please bring up this use case on #cxx (Slack) or [email protected].");
261   }
262 
263   template <typename Signature>
264   // NOLINTNEXTLINE(google-explicit-constructor)
265   operator FunctionRef<Signature>() && {
266     static_assert(
267         AlwaysFalse<Signature>,
268         "using base::BindOnce() is not necessary with base::FunctionRef; is it "
269         "possible to use a capturing lambda directly? If not, please bring up "
270         "this use case on #cxx (Slack) or [email protected].");
271   }
272 
273  private:
274   internal::BindStateHolder holder_;
275 };
276 
277 template <typename R, typename... Args>
278 class TRIVIAL_ABI RepeatingCallback<R(Args...)> {
279  public:
280   using ResultType = R;
281   using RunType = R(Args...);
282   using PolymorphicInvoke = R (*)(internal::BindStateBase*,
283                                   internal::PassingType<Args>...);
284 
285   // Constructs a null `RepeatingCallback`. A null callback has no associated
286   // functor and cannot be run.
287   constexpr RepeatingCallback() = default;
288   // Disallowed to prevent ambiguity.
289   RepeatingCallback(std::nullptr_t) = delete;
290 
291   // Unlike a `OnceCallback`, a `RepeatingCallback` may be copied since its
292   // bound functor may be run more than once.
293   RepeatingCallback(const RepeatingCallback&) = default;
294   RepeatingCallback& operator=(const RepeatingCallback&) = default;
295 
296   // Subtle: since `this` is marked as TRIVIAL_ABI, the move operations
297   // must leave the moved-from callback in a trivially destructible state.
298   RepeatingCallback(RepeatingCallback&&) noexcept = default;
299   RepeatingCallback& operator=(RepeatingCallback&&) noexcept = default;
300 
301   ~RepeatingCallback() = default;
302 
303   // Returns true if `this` is non-null and can be `Run()`.
304   explicit operator bool() const { return !!holder_; }
305   // Returns true if `this` is null and cannot be `Run()`.
is_null()306   bool is_null() const { return holder_.is_null(); }
307 
308   // Returns true if calling `Run()` is a no-op because of cancellation.
309   //
310   // - Not thread-safe, i.e. must be called on the same sequence that will
311   //   ultimately `Run()` the callback
312   // - May not be called on a null callback.
IsCancelled()313   bool IsCancelled() const { return holder_.IsCancelled(); }
314 
315   // Subtle version of `IsCancelled()` that allows cancellation state to be
316   // queried from any sequence. May return true even if the callback has
317   // actually been cancelled.
318   //
319   // Do not use. This is intended for internal //base usage.
320   // TODO(dcheng): Restrict this since it, in fact, being used outside of its
321   // originally intended use.
MaybeValid()322   bool MaybeValid() const { return holder_.MaybeValid(); }
323 
324   // Equality operators: two `RepeatingCallback`'s are equal
325   friend bool operator==(const RepeatingCallback&,
326                          const RepeatingCallback&) = default;
327 
328   // Resets this to null.
Reset()329   REINITIALIZES_AFTER_MOVE void Reset() { holder_.Reset(); }
330 
331   // Calls the bound functor with any already-bound arguments + `args`. Does not
332   // consume `this`, i.e. this remains non-null.
333   //
334   // May not be called on a null callback.
Run(Args...args)335   R Run(Args... args) const& {
336     CHECK(!holder_.is_null());
337 
338     // Keep `bind_state` alive at least until after the invocation to ensure all
339     // bound `Unretained` arguments remain protected by MiraclePtr.
340     scoped_refptr<internal::BindStateBase> bind_state = holder_.bind_state();
341 
342     PolymorphicInvoke f =
343         reinterpret_cast<PolymorphicInvoke>(holder_.polymorphic_invoke());
344     return f(bind_state.get(), std::forward<Args>(args)...);
345   }
346 
347   // Calls the bound functor with any already-bound arguments + `args`. Consumes
348   // `this`, i.e. `this` becomes null.
349   //
350   // May not be called on a null callback.
Run(Args...args)351   R Run(Args... args) && {
352     CHECK(!holder_.is_null());
353 
354     // Move the callback instance into a local variable before the invocation,
355     // that ensures the internal state is cleared after the invocation.
356     // It's not safe to touch |this| after the invocation, since running the
357     // bound function may destroy |this|.
358     internal::BindStateHolder holder = std::move(holder_);
359     PolymorphicInvoke f =
360         reinterpret_cast<PolymorphicInvoke>(holder.polymorphic_invoke());
361     return f(holder.bind_state().get(), std::forward<Args>(args)...);
362   }
363 
364   // Then() returns a new RepeatingCallback that receives the same arguments as
365   // |this|, and with the return type of |then|. The
366   // returned callback will:
367   // 1) Run the functor currently bound to |this| callback.
368   // 2) Run the |then| callback with the result from step 1 as its single
369   //    argument.
370   // 3) Return the value from running the |then| callback.
371   //
372   // If called on an rvalue (e.g. std::move(cb).Then(...)), this method
373   // generates a callback that is a replacement for `this`. Therefore, `this`
374   // will be consumed and reset to a null callback to ensure the
375   // originally-bound functor will be run at most once.
376   template <typename ThenR, typename... ThenArgs>
Then(RepeatingCallback<ThenR (ThenArgs...)> then)377   RepeatingCallback<ThenR(Args...)> Then(
378       RepeatingCallback<ThenR(ThenArgs...)> then) const& {
379     CHECK(then);
380     return BindRepeating(
381         internal::ThenHelper<
382             RepeatingCallback,
383             RepeatingCallback<ThenR(ThenArgs...)>>::CreateTrampoline(),
384         *this, std::move(then));
385   }
386 
387   template <typename ThenR, typename... ThenArgs>
Then(RepeatingCallback<ThenR (ThenArgs...)> then)388   RepeatingCallback<ThenR(Args...)> Then(
389       RepeatingCallback<ThenR(ThenArgs...)> then) && {
390     CHECK(then);
391     return BindRepeating(
392         internal::ThenHelper<
393             RepeatingCallback,
394             RepeatingCallback<ThenR(ThenArgs...)>>::CreateTrampoline(),
395         std::move(*this), std::move(then));
396   }
397 
398   // Internal constructors for various callback helper tag types, e.g.
399   // `base::DoNothing()`.
400 
401   // NOLINTNEXTLINE(google-explicit-constructor)
RepeatingCallback(internal::NullCallbackTag)402   constexpr RepeatingCallback(internal::NullCallbackTag)
403       : RepeatingCallback() {}
404   constexpr RepeatingCallback& operator=(internal::NullCallbackTag) {
405     *this = RepeatingCallback();
406     return *this;
407   }
408 
409   // NOLINTNEXTLINE(google-explicit-constructor)
RepeatingCallback(internal::NullCallbackTag::WithSignature<RunType>)410   constexpr RepeatingCallback(internal::NullCallbackTag::WithSignature<RunType>)
411       : RepeatingCallback(internal::NullCallbackTag()) {}
412   constexpr RepeatingCallback& operator=(
413       internal::NullCallbackTag::WithSignature<RunType>) {
414     *this = internal::NullCallbackTag();
415     return *this;
416   }
417 
418   // NOLINTNEXTLINE(google-explicit-constructor)
RepeatingCallback(internal::DoNothingCallbackTag)419   constexpr RepeatingCallback(internal::DoNothingCallbackTag)
420     requires(std::is_void_v<R>)
421       : RepeatingCallback(BindRepeating([](Args... args) {})) {}
422   constexpr RepeatingCallback& operator=(internal::DoNothingCallbackTag)
requires(std::is_void_v<R>)423     requires(std::is_void_v<R>)
424   {
425     *this = BindRepeating([](Args... args) {});
426     return *this;
427   }
428 
429   // NOLINTNEXTLINE(google-explicit-constructor)
RepeatingCallback(internal::DoNothingCallbackTag::WithSignature<RunType>)430   constexpr RepeatingCallback(
431       internal::DoNothingCallbackTag::WithSignature<RunType>)
432     requires(std::is_void_v<R>)
433       : RepeatingCallback(internal::DoNothingCallbackTag()) {}
434   constexpr RepeatingCallback& operator=(
435       internal::DoNothingCallbackTag::WithSignature<RunType>)
requires(std::is_void_v<R>)436     requires(std::is_void_v<R>)
437   {
438     *this = internal::DoNothingCallbackTag();
439     return *this;
440   }
441 
442   template <typename... BoundArgs>
443   // NOLINTNEXTLINE(google-explicit-constructor)
RepeatingCallback(internal::DoNothingCallbackTag::WithBoundArguments<BoundArgs...> tag)444   constexpr RepeatingCallback(
445       internal::DoNothingCallbackTag::WithBoundArguments<BoundArgs...> tag)
446     requires(std::is_void_v<R>)
447       : RepeatingCallback(
448             internal::ToDoNothingCallback<false, R, Args...>(std::move(tag))) {}
449   template <typename... BoundArgs>
450   constexpr RepeatingCallback& operator=(
451       internal::DoNothingCallbackTag::WithBoundArguments<BoundArgs...> tag)
requires(std::is_void_v<R>)452     requires(std::is_void_v<R>)
453   {
454     *this = internal::ToDoNothingCallback<false, R, Args...>(std::move(tag));
455     return this;
456   }
457 
458   // Internal constructor for `base::BindRepeating()`.
RepeatingCallback(internal::BindStateBase * bind_state)459   explicit RepeatingCallback(internal::BindStateBase* bind_state)
460       : holder_(bind_state) {}
461 
462   template <typename Signature>
463   // NOLINTNEXTLINE(google-explicit-constructor)
464   operator FunctionRef<Signature>() & {
465     static_assert(
466         AlwaysFalse<Signature>,
467         "need to convert a base::RepeatingCallback to base::FunctionRef? "
468         "Please bring up this use case on #cxx (Slack) or [email protected].");
469   }
470 
471   template <typename Signature>
472   // NOLINTNEXTLINE(google-explicit-constructor)
473   operator FunctionRef<Signature>() && {
474     static_assert(
475         AlwaysFalse<Signature>,
476         "using base::BindRepeating() is not necessary with base::FunctionRef; "
477         "is it possible to use a capturing lambda directly? If not, please "
478         "bring up this use case on #cxx (Slack) or [email protected].");
479   }
480 
481  private:
482   friend class OnceCallback<R(Args...)>;
483 
484   internal::BindStateHolder holder_;
485 };
486 
487 namespace internal {
488 
489 // Helper for the `DoNothingWithBoundArgs()` implementation.
490 // Unlike the other helpers, this cannot be easily moved to callback_internal.h,
491 // since it depends on `BindOnce()` and `BindRepeating()`.
492 template <bool is_once,
493           typename R,
494           typename... UnboundArgs,
495           typename... BoundArgs>
ToDoNothingCallback(DoNothingCallbackTag::WithBoundArguments<BoundArgs...> t)496 auto ToDoNothingCallback(
497     DoNothingCallbackTag::WithBoundArguments<BoundArgs...> t) {
498   return std::apply(
499       [](auto&&... args) {
500         if constexpr (is_once) {
501           return BindOnce([](TransformToUnwrappedType<is_once, BoundArgs>...,
502                              UnboundArgs...) {},
503                           std::move(args)...);
504         } else {
505           return BindRepeating(
506               [](TransformToUnwrappedType<is_once, BoundArgs>...,
507                  UnboundArgs...) {},
508               std::move(args)...);
509         }
510       },
511       std::move(t.bound_args));
512 }
513 
514 }  // namespace internal
515 
516 }  // namespace base
517 
518 #endif  // BASE_FUNCTIONAL_CALLBACK_H_
519