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