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 // This file contains utility functions and classes that help the
6 // implementation, and management of the Callback objects.
7
8 #ifndef BASE_FUNCTIONAL_CALLBACK_INTERNAL_H_
9 #define BASE_FUNCTIONAL_CALLBACK_INTERNAL_H_
10
11 #include <type_traits>
12 #include <utility>
13
14 #include "base/base_export.h"
15 #include "base/compiler_specific.h"
16 #include "base/functional/callback_forward.h"
17 #include "base/memory/ref_counted.h"
18
19 namespace base {
20
21 struct FakeBindState;
22
23 namespace internal {
24
25 class BindStateBase;
26
27 template <bool is_method,
28 bool is_nullable,
29 bool is_callback,
30 typename Functor,
31 typename... BoundArgs>
32 struct BindState;
33
34 struct BASE_EXPORT BindStateBaseRefCountTraits {
35 static void Destruct(const BindStateBase*);
36 };
37
38 template <typename T>
39 using PassingType = std::conditional_t<std::is_scalar_v<T>, T, T&&>;
40
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
46 // "type erasure."
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> {
53 public:
54 REQUIRE_ADOPTION_FOR_REFCOUNTED_TYPE();
55
56 // What kind of cancellation query the call to the cancellation traits is
57 // making. This enum could be removed, at the cost of storing an extra
58 // function pointer.
59 enum class CancellationQueryMode : bool {
60 kIsCancelled = false,
61 kMaybeValid = true,
62 };
63
64 using InvokeFuncStorage = void (*)();
65
66 BindStateBase(const BindStateBase&) = delete;
67 BindStateBase& operator=(const BindStateBase&) = delete;
68
69 private:
70 using DestructorPtr = void (*)(const BindStateBase*);
71 using QueryCancellationTraitsPtr = bool (*)(const BindStateBase*,
72 CancellationQueryMode mode);
73
74 BindStateBase(InvokeFuncStorage polymorphic_invoke, DestructorPtr destructor);
75 BindStateBase(InvokeFuncStorage polymorphic_invoke,
76 DestructorPtr destructor,
77 QueryCancellationTraitsPtr query_cancellation_traits);
78 ~BindStateBase() = default;
79
80 friend struct BindStateBaseRefCountTraits;
81 friend class RefCountedThreadSafe<BindStateBase, BindStateBaseRefCountTraits>;
82
83 friend class BindStateHolder;
84
85 // Allowlist subclasses that access the destructor of BindStateBase.
86 template <bool is_method,
87 bool is_nullable,
88 bool is_callback,
89 typename Functor,
90 typename... BoundArgs>
91 friend struct BindState;
92 friend struct ::base::FakeBindState;
93
IsCancelled()94 bool IsCancelled() const {
95 return query_cancellation_traits_(this,
96 CancellationQueryMode::kIsCancelled);
97 }
98
MaybeValid()99 bool MaybeValid() const {
100 return query_cancellation_traits_(this, CancellationQueryMode::kMaybeValid);
101 }
102
103 // In C++, it is safe to cast function pointers to function pointers of
104 // another type. It is not okay to use void*. We create a InvokeFuncStorage
105 // that that can store our function pointer, and then cast it back to
106 // the original type on usage.
107 InvokeFuncStorage polymorphic_invoke_;
108
109 // Pointer to a function that will properly destroy |this|.
110 DestructorPtr destructor_;
111 QueryCancellationTraitsPtr query_cancellation_traits_;
112 };
113
114 // Minimal wrapper around a `scoped_refptr<BindStateBase>`. It allows more
115 // expensive operations (such as ones that destroy `BindStateBase` or manipulate
116 // refcounts) to be defined out-of-line to reduce binary size.
117 class BASE_EXPORT TRIVIAL_ABI BindStateHolder {
118 public:
119 using InvokeFuncStorage = BindStateBase::InvokeFuncStorage;
120
121 // Used to construct a null callback.
122 inline constexpr BindStateHolder() noexcept;
123
124 // Used to construct a callback by `base::BindOnce()`/`base::BindRepeating().
125 inline explicit BindStateHolder(BindStateBase* bind_state);
126
127 // BindStateHolder is always copyable so it can be used by `OnceCallback` and
128 // `RepeatingCallback`. `OnceCallback` restricts copies so a `BindStateHolder`
129 // used with a `OnceCallback will never be copied.
130 BindStateHolder(const BindStateHolder&);
131 BindStateHolder& operator=(const BindStateHolder&);
132
133 // Subtle: since `this` is marked as TRIVIAL_ABI, the move operations must
134 // leave a moved-from `BindStateHolder` in a trivially destructible state.
135 inline BindStateHolder(BindStateHolder&&) noexcept;
136 BindStateHolder& operator=(BindStateHolder&&) noexcept;
137
138 ~BindStateHolder();
139
is_null()140 bool is_null() const { return !bind_state_; }
141 explicit operator bool() const { return !is_null(); }
142
143 bool IsCancelled() const;
144 bool MaybeValid() const;
145
146 void Reset();
147
148 friend bool operator==(const BindStateHolder&,
149 const BindStateHolder&) = default;
150
bind_state()151 const scoped_refptr<BindStateBase>& bind_state() const { return bind_state_; }
152
polymorphic_invoke()153 InvokeFuncStorage polymorphic_invoke() const {
154 return bind_state_->polymorphic_invoke_;
155 }
156
157 private:
158 scoped_refptr<BindStateBase> bind_state_;
159 };
160
161 constexpr BindStateHolder::BindStateHolder() noexcept = default;
162
163 // TODO(dcheng): Try plumbing a scoped_refptr all the way through, since
164 // scoped_refptr is marked as TRIVIAL_ABI.
BindStateHolder(BindStateBase * bind_state)165 BindStateHolder::BindStateHolder(BindStateBase* bind_state)
166 : bind_state_(AdoptRef(bind_state)) {}
167
168 // Unlike the copy constructor, copy assignment operator, and move assignment
169 // operator, the move constructor is defaulted in the header because it
170 // generates minimal code: move construction does not change any refcounts, nor
171 // does it potentially destroy `BindStateBase`.
172 BindStateHolder::BindStateHolder(BindStateHolder&&) noexcept = default;
173
174 // Helpers for the `Then()` implementation.
175 template <typename OriginalCallback, typename ThenCallback>
176 struct ThenHelper;
177
178 // Specialization when original callback returns `void`.
179 template <template <typename> class OriginalCallback,
180 template <typename>
181 class ThenCallback,
182 typename... OriginalArgs,
183 typename ThenR,
184 typename... ThenArgs>
185 struct ThenHelper<OriginalCallback<void(OriginalArgs...)>,
186 ThenCallback<ThenR(ThenArgs...)>> {
187 private:
188 // For context on this "templated struct with a lambda that asserts" pattern,
189 // see comments in `Invoker<>`.
190 template <bool v = sizeof...(ThenArgs) == 0>
191 struct CorrectNumberOfArgs {
192 static constexpr bool value = [] {
193 static_assert(v,
194 "|then| callback cannot accept parameters if |this| has a "
195 "void return type.");
196 return v;
197 }();
198 };
199
200 public:
201 static auto CreateTrampoline() {
202 return [](OriginalCallback<void(OriginalArgs...)> c1,
203 ThenCallback<ThenR(ThenArgs...)> c2,
204 OriginalArgs... c1_args) -> ThenR {
205 if constexpr (CorrectNumberOfArgs<>::value) {
206 std::move(c1).Run(std::forward<OriginalArgs>(c1_args)...);
207 return std::move(c2).Run();
208 }
209 };
210 }
211 };
212
213 // Specialization when original callback returns a non-void type.
214 template <template <typename> class OriginalCallback,
215 template <typename>
216 class ThenCallback,
217 typename OriginalR,
218 typename... OriginalArgs,
219 typename ThenR,
220 typename... ThenArgs>
221 struct ThenHelper<OriginalCallback<OriginalR(OriginalArgs...)>,
222 ThenCallback<ThenR(ThenArgs...)>> {
223 private:
224 template <bool v = sizeof...(ThenArgs) == 1>
225 struct CorrectNumberOfArgs {
226 static constexpr bool value = [] {
227 static_assert(
228 v,
229 "|then| callback must accept exactly one parameter if |this| has a "
230 "non-void return type.");
231 return v;
232 }();
233 };
234
235 template <bool v =
236 // TODO(dcheng): This should probably check is_convertible as
237 // well (same with `AssertBindArgsValidity`).
238 std::is_constructible_v<ThenArgs..., OriginalR&&>>
239 struct ArgsAreConvertible {
240 static constexpr bool value = [] {
241 static_assert(v,
242 "|then| callback's parameter must be constructible from "
243 "return type of |this|.");
244 return v;
245 }();
246 };
247
248 public:
249 static auto CreateTrampoline() {
250 return [](OriginalCallback<OriginalR(OriginalArgs...)> c1,
251 ThenCallback<ThenR(ThenArgs...)> c2,
252 OriginalArgs... c1_args) -> ThenR {
253 if constexpr (std::conjunction_v<CorrectNumberOfArgs<>,
254 ArgsAreConvertible<>>) {
255 return std::move(c2).Run(
256 std::move(c1).Run(std::forward<OriginalArgs>(c1_args)...));
257 }
258 };
259 }
260 };
261
262 } // namespace internal
263 } // namespace base
264
265 #endif // BASE_FUNCTIONAL_CALLBACK_INTERNAL_H_
266