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