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.
5 // This file contains utility functions and classes that help the
6 // implementation, and management of the Callback objects.
8 #ifndef BASE_CALLBACK_INTERNAL_H_
9 #define BASE_CALLBACK_INTERNAL_H_
11 #include "base/base_export.h"
12 #include "base/callback_forward.h"
13 #include "base/memory/ref_counted.h"
22 class FinallyExecutorCommon;
23 class ThenAndCatchExecutorCommon;
25 template <typename ReturnType>
26 class PostTaskExecutor;
28 template <typename Functor, typename... BoundArgs>
32 class CallbackBaseCopyable;
34 struct BindStateBaseRefCountTraits {
35 static void Destruct(const BindStateBase*);
39 using PassingType = std::conditional_t<std::is_scalar<T>::value, T, T&&>;
41 // BindStateBase is used to provide an opaque handle that the Callback
42 // class can use to represent a function object with bound arguments. It
43 // behaves as an existential type that is used by a corresponding
44 // DoInvoke function to perform the function execution. This allows
45 // us to shield the Callback class from the types of the bound argument via
47 // At the base level, the only task is to add reference counting data. Avoid
48 // using or inheriting any virtual functions. Creating a vtable for every
49 // BindState template instantiation results in a lot of bloat. Its only task is
50 // to call the destructor which can be done with a function pointer.
51 class BASE_EXPORT BindStateBase
52 : public RefCountedThreadSafe<BindStateBase, BindStateBaseRefCountTraits> {
54 REQUIRE_ADOPTION_FOR_REFCOUNTED_TYPE();
56 enum CancellationQueryMode {
61 using InvokeFuncStorage = void(*)();
63 BindStateBase(const BindStateBase&) = delete;
64 BindStateBase& operator=(const BindStateBase&) = delete;
67 BindStateBase(InvokeFuncStorage polymorphic_invoke,
68 void (*destructor)(const BindStateBase*));
69 BindStateBase(InvokeFuncStorage polymorphic_invoke,
70 void (*destructor)(const BindStateBase*),
71 bool (*query_cancellation_traits)(const BindStateBase*,
72 CancellationQueryMode mode));
74 ~BindStateBase() = default;
76 friend struct BindStateBaseRefCountTraits;
77 friend class RefCountedThreadSafe<BindStateBase, BindStateBaseRefCountTraits>;
79 friend class CallbackBase;
80 friend class CallbackBaseCopyable;
82 // Allowlist subclasses that access the destructor of BindStateBase.
83 template <typename Functor, typename... BoundArgs>
84 friend struct BindState;
85 friend struct ::base::FakeBindState;
87 bool IsCancelled() const {
88 return query_cancellation_traits_(this, IS_CANCELLED);
91 bool MaybeValid() const {
92 return query_cancellation_traits_(this, MAYBE_VALID);
95 // In C++, it is safe to cast function pointers to function pointers of
96 // another type. It is not okay to use void*. We create a InvokeFuncStorage
97 // that that can store our function pointer, and then cast it back to
98 // the original type on usage.
99 InvokeFuncStorage polymorphic_invoke_;
101 // Pointer to a function that will properly destroy |this|.
102 void (*destructor_)(const BindStateBase*);
103 bool (*query_cancellation_traits_)(const BindStateBase*,
104 CancellationQueryMode mode);
107 // Holds the Callback methods that don't require specialization to reduce
109 // CallbackBase<MoveOnly> is a direct base class of MoveOnly callbacks, and
110 // CallbackBase<Copyable> uses CallbackBase<MoveOnly> for its implementation.
111 class BASE_EXPORT CallbackBase {
113 inline CallbackBase(CallbackBase&& c) noexcept;
114 CallbackBase& operator=(CallbackBase&& c) noexcept;
116 explicit CallbackBase(const CallbackBaseCopyable& c);
117 CallbackBase& operator=(const CallbackBaseCopyable& c);
119 explicit CallbackBase(CallbackBaseCopyable&& c) noexcept;
120 CallbackBase& operator=(CallbackBaseCopyable&& c) noexcept;
122 // Returns true if Callback is null (doesn't refer to anything).
123 bool is_null() const { return !bind_state_; }
124 explicit operator bool() const { return !is_null(); }
126 // Returns true if the callback invocation will be nop due to an cancellation.
127 // It's invalid to call this on uninitialized callback.
129 // Must be called on the Callback's destination sequence.
130 bool IsCancelled() const;
132 // If this returns false, the callback invocation will be a nop due to a
133 // cancellation. This may(!) still return true, even on a cancelled callback.
135 // This function is thread-safe.
136 bool MaybeValid() const;
138 // Returns the Callback into an uninitialized state.
142 friend class FinallyExecutorCommon;
143 friend class ThenAndCatchExecutorCommon;
145 template <typename ReturnType>
146 friend class PostTaskExecutor;
148 using InvokeFuncStorage = BindStateBase::InvokeFuncStorage;
150 // Returns true if this callback equals |other|. |other| may be null.
151 bool EqualsInternal(const CallbackBase& other) const;
153 constexpr inline CallbackBase();
155 // Allow initializing of |bind_state_| via the constructor to avoid default
156 // initialization of the scoped_refptr.
157 explicit inline CallbackBase(BindStateBase* bind_state);
159 InvokeFuncStorage polymorphic_invoke() const {
160 return bind_state_->polymorphic_invoke_;
163 // Force the destructor to be instantiated inside this translation unit so
164 // that our subclasses will not get inlined versions. Avoids more template
168 scoped_refptr<BindStateBase> bind_state_;
171 constexpr CallbackBase::CallbackBase() = default;
172 CallbackBase::CallbackBase(CallbackBase&&) noexcept = default;
173 CallbackBase::CallbackBase(BindStateBase* bind_state)
174 : bind_state_(AdoptRef(bind_state)) {}
176 // CallbackBase<Copyable> is a direct base class of Copyable Callbacks.
177 class BASE_EXPORT CallbackBaseCopyable : public CallbackBase {
179 CallbackBaseCopyable(const CallbackBaseCopyable& c);
180 CallbackBaseCopyable(CallbackBaseCopyable&& c) noexcept = default;
181 CallbackBaseCopyable& operator=(const CallbackBaseCopyable& c);
182 CallbackBaseCopyable& operator=(CallbackBaseCopyable&& c) noexcept;
185 constexpr CallbackBaseCopyable() = default;
186 explicit CallbackBaseCopyable(BindStateBase* bind_state)
187 : CallbackBase(bind_state) {}
188 ~CallbackBaseCopyable() = default;
191 // Helpers for the `Then()` implementation.
192 template <typename OriginalCallback, typename ThenCallback>
195 // Specialization when original callback returns `void`.
196 template <template <typename> class OriginalCallback,
199 typename... OriginalArgs,
201 typename... ThenArgs>
202 struct ThenHelper<OriginalCallback<void(OriginalArgs...)>,
203 ThenCallback<ThenR(ThenArgs...)>> {
204 static_assert(sizeof...(ThenArgs) == 0,
205 "|then| callback cannot accept parameters if |this| has a "
206 "void return type.");
208 static auto CreateTrampoline() {
209 return [](OriginalCallback<void(OriginalArgs...)> c1,
210 ThenCallback<ThenR(ThenArgs...)> c2, OriginalArgs... c1_args) {
211 std::move(c1).Run(std::forward<OriginalArgs>(c1_args)...);
212 return std::move(c2).Run();
217 // Specialization when original callback returns a non-void type.
218 template <template <typename> class OriginalCallback,
222 typename... OriginalArgs,
224 typename... ThenArgs>
225 struct ThenHelper<OriginalCallback<OriginalR(OriginalArgs...)>,
226 ThenCallback<ThenR(ThenArgs...)>> {
227 static_assert(sizeof...(ThenArgs) == 1,
228 "|then| callback must accept exactly one parameter if |this| "
229 "has a non-void return type.");
230 // TODO(dcheng): This should probably check is_convertible as well (same with
231 // `AssertBindArgsValidity`).
232 static_assert(std::is_constructible<ThenArgs..., OriginalR&&>::value,
233 "|then| callback's parameter must be constructible from "
234 "return type of |this|.");
236 static auto CreateTrampoline() {
237 return [](OriginalCallback<OriginalR(OriginalArgs...)> c1,
238 ThenCallback<ThenR(ThenArgs...)> c2, OriginalArgs... c1_args) {
239 return std::move(c2).Run(
240 std::move(c1).Run(std::forward<OriginalArgs>(c1_args)...));
245 } // namespace internal
248 #endif // BASE_CALLBACK_INTERNAL_H_