123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333 |
- // Copyright (c) 2012 The Chromium Authors. All rights reserved.
- // 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/callback_forward.h" instead of this file.
- #ifndef BASE_CALLBACK_H_
- #define BASE_CALLBACK_H_
- #include <stddef.h>
- #include <utility>
- #include "base/bind.h"
- #include "base/callback_forward.h" // IWYU pragma: export
- #include "base/callback_internal.h"
- #include "base/check.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 {
- struct NullCallbackTag {
- template <typename Signature>
- struct WithSignature {};
- };
- struct DoNothingCallbackTag {
- template <typename Signature>
- struct WithSignature {};
- };
- } // namespace internal
- template <typename R, typename... Args>
- class OnceCallback<R(Args...)> : public internal::CallbackBase {
- public:
- using ResultType = R;
- using RunType = R(Args...);
- using PolymorphicInvoke = R (*)(internal::BindStateBase*,
- internal::PassingType<Args>...);
- constexpr OnceCallback() = default;
- OnceCallback(std::nullptr_t) = delete;
- constexpr OnceCallback(internal::NullCallbackTag) : OnceCallback() {}
- constexpr OnceCallback& operator=(internal::NullCallbackTag) {
- *this = OnceCallback();
- return *this;
- }
- constexpr OnceCallback(internal::NullCallbackTag::WithSignature<RunType>)
- : OnceCallback(internal::NullCallbackTag()) {}
- constexpr OnceCallback& operator=(
- internal::NullCallbackTag::WithSignature<RunType>) {
- *this = internal::NullCallbackTag();
- return *this;
- }
- constexpr OnceCallback(internal::DoNothingCallbackTag)
- : OnceCallback(BindOnce([](Args... args) {})) {}
- constexpr OnceCallback& operator=(internal::DoNothingCallbackTag) {
- *this = BindOnce([](Args... args) {});
- return *this;
- }
- constexpr OnceCallback(internal::DoNothingCallbackTag::WithSignature<RunType>)
- : OnceCallback(internal::DoNothingCallbackTag()) {}
- constexpr OnceCallback& operator=(
- internal::DoNothingCallbackTag::WithSignature<RunType>) {
- *this = internal::DoNothingCallbackTag();
- return *this;
- }
- explicit OnceCallback(internal::BindStateBase* bind_state)
- : internal::CallbackBase(bind_state) {}
- OnceCallback(const OnceCallback&) = delete;
- OnceCallback& operator=(const OnceCallback&) = delete;
- OnceCallback(OnceCallback&&) noexcept = default;
- OnceCallback& operator=(OnceCallback&&) noexcept = default;
- OnceCallback(RepeatingCallback<RunType> other)
- : internal::CallbackBase(std::move(other)) {}
- OnceCallback& operator=(RepeatingCallback<RunType> other) {
- static_cast<internal::CallbackBase&>(*this) = std::move(other);
- return *this;
- }
- 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();
- }
- R Run(Args... args) && {
- // 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|.
- OnceCallback cb = std::move(*this);
- PolymorphicInvoke f =
- reinterpret_cast<PolymorphicInvoke>(cb.polymorphic_invoke());
- return f(cb.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 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 BindOnce(
- internal::ThenHelper<
- OnceCallback,
- RepeatingCallback<ThenR(ThenArgs...)>>::CreateTrampoline(),
- std::move(*this), std::move(then));
- }
- 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.");
- }
- };
- template <typename R, typename... Args>
- class RepeatingCallback<R(Args...)> : public internal::CallbackBaseCopyable {
- public:
- using ResultType = R;
- using RunType = R(Args...);
- using PolymorphicInvoke = R (*)(internal::BindStateBase*,
- internal::PassingType<Args>...);
- constexpr RepeatingCallback() = default;
- RepeatingCallback(std::nullptr_t) = delete;
- constexpr RepeatingCallback(internal::NullCallbackTag)
- : RepeatingCallback() {}
- constexpr RepeatingCallback& operator=(internal::NullCallbackTag) {
- *this = RepeatingCallback();
- return *this;
- }
- constexpr RepeatingCallback(internal::NullCallbackTag::WithSignature<RunType>)
- : RepeatingCallback(internal::NullCallbackTag()) {}
- constexpr RepeatingCallback& operator=(
- internal::NullCallbackTag::WithSignature<RunType>) {
- *this = internal::NullCallbackTag();
- return *this;
- }
- constexpr RepeatingCallback(internal::DoNothingCallbackTag)
- : RepeatingCallback(BindRepeating([](Args... args) {})) {}
- constexpr RepeatingCallback& operator=(internal::DoNothingCallbackTag) {
- *this = BindRepeating([](Args... args) {});
- return *this;
- }
- constexpr RepeatingCallback(
- internal::DoNothingCallbackTag::WithSignature<RunType>)
- : RepeatingCallback(internal::DoNothingCallbackTag()) {}
- constexpr RepeatingCallback& operator=(
- internal::DoNothingCallbackTag::WithSignature<RunType>) {
- *this = internal::DoNothingCallbackTag();
- return *this;
- }
- explicit RepeatingCallback(internal::BindStateBase* bind_state)
- : internal::CallbackBaseCopyable(bind_state) {}
- // Copyable and movable.
- RepeatingCallback(const RepeatingCallback&) = default;
- RepeatingCallback& operator=(const RepeatingCallback&) = default;
- RepeatingCallback(RepeatingCallback&&) noexcept = default;
- RepeatingCallback& operator=(RepeatingCallback&&) noexcept = default;
- bool operator==(const RepeatingCallback& other) const {
- return EqualsInternal(other);
- }
- bool operator!=(const RepeatingCallback& other) const {
- return !operator==(other);
- }
- R Run(Args... args) const & {
- PolymorphicInvoke f =
- reinterpret_cast<PolymorphicInvoke>(this->polymorphic_invoke());
- return f(this->bind_state_.get(), std::forward<Args>(args)...);
- }
- R Run(Args... args) && {
- // 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|.
- RepeatingCallback cb = std::move(*this);
- PolymorphicInvoke f =
- reinterpret_cast<PolymorphicInvoke>(cb.polymorphic_invoke());
- return f(std::move(cb).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));
- }
- 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.");
- }
- };
- } // namespace base
- #endif // BASE_CALLBACK_H_
|