1 // Copyright 2011 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 #ifndef BASE_FUNCTIONAL_BIND_H_
6 #define BASE_FUNCTIONAL_BIND_H_
7
8 #include <functional>
9 #include <memory>
10 #include <type_traits>
11 #include <utility>
12
13 #include "base/compiler_specific.h"
14 #include "base/functional/bind_internal.h"
15 #include "base/memory/raw_ptr.h"
16 #include "build/build_config.h"
17
18 // -----------------------------------------------------------------------------
19 // Usage documentation
20 // -----------------------------------------------------------------------------
21 //
22 // Overview:
23 // base::BindOnce() and base::BindRepeating() are helpers for creating
24 // base::OnceCallback and base::RepeatingCallback objects respectively.
25 //
26 // For a runnable object of n-arity, the base::Bind*() family allows partial
27 // application of the first m arguments. The remaining n - m arguments must be
28 // passed when invoking the callback with Run().
29 //
30 // // The first argument is bound at callback creation; the remaining
31 // // two must be passed when calling Run() on the callback object.
32 // base::OnceCallback<long(int, long)> cb = base::BindOnce(
33 // [](short x, int y, long z) { return x * y * z; }, 42);
34 //
35 // When binding to a method, the receiver object must also be specified at
36 // callback creation time. When Run() is invoked, the method will be invoked on
37 // the specified receiver object.
38 //
39 // class C : public base::RefCounted<C> { void F(); };
40 // auto instance = base::MakeRefCounted<C>();
41 // auto cb = base::BindOnce(&C::F, instance);
42 // std::move(cb).Run(); // Identical to instance->F()
43 //
44 // See //docs/callback.md for the full documentation.
45 //
46 // -----------------------------------------------------------------------------
47 // Implementation notes
48 // -----------------------------------------------------------------------------
49 //
50 // If you're reading the implementation, before proceeding further, you should
51 // read the top comment of base/functional/bind_internal.h for a definition of
52 // common terms and concepts.
53
54 namespace base {
55
56 // Bind as OnceCallback.
57 template <typename Functor, typename... Args>
BindOnce(Functor && functor,Args &&...args)58 inline auto BindOnce(Functor&& functor, Args&&... args) {
59 return internal::BindHelper<OnceCallback>::Bind(
60 std::forward<Functor>(functor), std::forward<Args>(args)...);
61 }
62
63 // Bind as RepeatingCallback.
64 template <typename Functor, typename... Args>
BindRepeating(Functor && functor,Args &&...args)65 inline auto BindRepeating(Functor&& functor, Args&&... args) {
66 return internal::BindHelper<RepeatingCallback>::Bind(
67 std::forward<Functor>(functor), std::forward<Args>(args)...);
68 }
69
70 // Overloads to allow nicer compile errors when attempting to pass the address
71 // an overloaded function to `BindOnce()` or `BindRepeating()`. Otherwise, clang
72 // provides only the error message "no matching function [...] candidate
73 // template ignored: couldn't infer template argument 'Functor'", with no
74 // reference to the fact that `&` is being used on an overloaded function.
75 //
76 // These overloads to provide better error messages will never be selected
77 // unless template type deduction fails because of how overload resolution
78 // works; per [over.ics.rank/2.2]:
79 //
80 // When comparing the basic forms of implicit conversion sequences (as defined
81 // in [over.best.ics])
82 // - a standard conversion sequence is a better conversion sequence than a
83 // user-defined conversion sequence or an ellipsis conversion sequence, and
84 // - a user-defined conversion sequence is a better conversion sequence than
85 // an ellipsis conversion sequence.
86 //
87 // So these overloads will only be selected as a last resort iff template type
88 // deduction fails.
89 BindFailedCheckPreviousErrors BindOnce(...);
90 BindFailedCheckPreviousErrors BindRepeating(...);
91
92 // Unretained(), UnsafeDangling() and UnsafeDanglingUntriaged() allow binding a
93 // non-refcounted class, and to disable refcounting on arguments that are
94 // refcounted. The main difference is whether or not the raw pointers will be
95 // checked for dangling references (e.g. a pointer that points to an already
96 // destroyed object) when the callback is run.
97 //
98 // It is _required_ to use one of Unretained(), UnsafeDangling() or
99 // UnsafeDanglingUntriaged() for raw pointer receivers now. For other arguments,
100 // it remains optional. If not specified, default behavior is Unretained().
101
102 // Unretained() pointers will be checked for dangling pointers when the
103 // callback is run, *if* the callback has not been cancelled.
104 //
105 // Example of Unretained() usage:
106 //
107 // class Foo {
108 // public:
109 // void func() { cout << "Foo:f" << endl; }
110 // };
111 //
112 // // In some function somewhere.
113 // Foo foo;
114 // OnceClosure foo_callback =
115 // BindOnce(&Foo::func, Unretained(&foo));
116 // std::move(foo_callback).Run(); // Prints "Foo:f".
117 //
118 // Without the Unretained() wrapper on |&foo|, the above call would fail
119 // to compile because Foo does not support the AddRef() and Release() methods.
120 //
121 // Unretained() does not allow dangling pointers, e.g.:
122 // class MyClass {
123 // public:
124 // OnError(int error);
125 // private:
126 // scoped_refptr<base::TaskRunner> runner_;
127 // std::unique_ptr<AnotherClass> obj_;
128 // };
129 //
130 // void MyClass::OnError(int error) {
131 // // the pointer (which is also the receiver here) to `AnotherClass`
132 // // might dangle depending on when the task is invoked.
133 // runner_->PostTask(FROM_HERE, base::BindOnce(&AnotherClass::OnError,
134 // base::Unretained(obj_.get()), error));
135 // // one of the way to solve this issue here would be:
136 // // runner_->PostTask(FROM_HERE,
137 // // base::BindOnce(&AnotherClass::OnError,
138 // // base::Owned(std::move(obj_)), error));
139 // delete this;
140 // }
141 //
142 // the above example is a BAD USAGE of Unretained(), which might result in a
143 // use-after-free, as `AnotherClass::OnError` might be invoked with a dangling
144 // pointer as receiver.
145 template <typename T>
Unretained(T * o)146 inline auto Unretained(T* o) {
147 return internal::UnretainedWrapper<T, unretained_traits::MayNotDangle>(o);
148 }
149
150 template <typename T, RawPtrTraits Traits>
Unretained(const raw_ptr<T,Traits> & o)151 inline auto Unretained(const raw_ptr<T, Traits>& o) {
152 return internal::UnretainedWrapper<T, unretained_traits::MayNotDangle,
153 Traits>(o);
154 }
155
156 template <typename T, RawPtrTraits Traits>
Unretained(raw_ptr<T,Traits> && o)157 inline auto Unretained(raw_ptr<T, Traits>&& o) {
158 return internal::UnretainedWrapper<T, unretained_traits::MayNotDangle,
159 Traits>(std::move(o));
160 }
161
162 template <typename T, RawPtrTraits Traits>
Unretained(const raw_ref<T,Traits> & o)163 inline auto Unretained(const raw_ref<T, Traits>& o) {
164 return internal::UnretainedRefWrapper<T, unretained_traits::MayNotDangle,
165 Traits>(o);
166 }
167
168 template <typename T, RawPtrTraits Traits>
Unretained(raw_ref<T,Traits> && o)169 inline auto Unretained(raw_ref<T, Traits>&& o) {
170 return internal::UnretainedRefWrapper<T, unretained_traits::MayNotDangle,
171 Traits>(std::move(o));
172 }
173
174 // Similar to `Unretained()`, but allows dangling pointers, e.g.:
175 //
176 // class MyClass {
177 // public:
178 // DoSomething(HandlerClass* handler);
179 // private:
180 // void MyClass::DoSomethingInternal(HandlerClass::Id id,
181 // HandlerClass* handler);
182 //
183 // std::unordered_map<HandlerClass::Id, HandlerClass*> handlers_;
184 // scoped_refptr<base::SequencedTaskRunner> runner_;
185 // base::Lock lock_;
186 // };
187 // void MyClass::DoSomething(HandlerClass* handler) {
188 // runner_->PostTask(FROM_HERE,
189 // base::BindOnce(&MyClass::DoSomethingInternal,
190 // base::Unretained(this),
191 // handler->id(),
192 // base::Unretained(handler)));
193 // }
194 // void MyClass::DoSomethingInternal(HandlerClass::Id id,
195 // HandlerClass* handler) {
196 // base::AutoLock locker(lock_);
197 // if (handlers_.find(id) == std::end(handlers_)) return;
198 // // Now we can use `handler`.
199 // }
200 //
201 // As `DoSomethingInternal` is run on a sequence (and we can imagine
202 // `handlers_` being modified on it as well), we protect the function from
203 // using a dangling `handler` by making sure it is still contained in the
204 // map.
205 //
206 // Strongly prefer `Unretained()`. This is useful in limited situations such as
207 // the one above.
208 //
209 // When using `UnsafeDangling()`, the receiver must be of type MayBeDangling<>.
210 template <typename T>
UnsafeDangling(T * o)211 inline auto UnsafeDangling(T* o) {
212 return internal::UnretainedWrapper<T, unretained_traits::MayDangle>(o);
213 }
214
215 template <typename T, RawPtrTraits Traits>
UnsafeDangling(const raw_ptr<T,Traits> & o)216 auto UnsafeDangling(const raw_ptr<T, Traits>& o) {
217 return internal::UnretainedWrapper<T, unretained_traits::MayDangle, Traits>(
218 o);
219 }
220
221 template <typename T, RawPtrTraits Traits>
UnsafeDangling(raw_ptr<T,Traits> && o)222 auto UnsafeDangling(raw_ptr<T, Traits>&& o) {
223 return internal::UnretainedWrapper<T, unretained_traits::MayDangle, Traits>(
224 std::move(o));
225 }
226
227 template <typename T, RawPtrTraits Traits>
UnsafeDangling(const raw_ref<T,Traits> & o)228 auto UnsafeDangling(const raw_ref<T, Traits>& o) {
229 return internal::UnretainedRefWrapper<T, unretained_traits::MayDangle,
230 Traits>(o);
231 }
232
233 template <typename T, RawPtrTraits Traits>
UnsafeDangling(raw_ref<T,Traits> && o)234 auto UnsafeDangling(raw_ref<T, Traits>&& o) {
235 return internal::UnretainedRefWrapper<T, unretained_traits::MayDangle,
236 Traits>(std::move(o));
237 }
238
239 // Like `UnsafeDangling()`, but used to annotate places that still need to be
240 // triaged and either migrated to `Unretained()` and safer ownership patterns
241 // (preferred) or `UnsafeDangling()` if the correct pattern to use is the one
242 // in the `UnsafeDangling()` example above for example.
243 //
244 // Unlike `UnsafeDangling()`, the receiver doesn't have to be MayBeDangling<>.
245 template <typename T>
UnsafeDanglingUntriaged(T * o)246 inline auto UnsafeDanglingUntriaged(T* o) {
247 return internal::UnretainedWrapper<T, unretained_traits::MayDangleUntriaged>(
248 o);
249 }
250
251 template <typename T, RawPtrTraits Traits>
UnsafeDanglingUntriaged(const raw_ptr<T,Traits> & o)252 auto UnsafeDanglingUntriaged(const raw_ptr<T, Traits>& o) {
253 return internal::UnretainedWrapper<T, unretained_traits::MayDangleUntriaged,
254 Traits>(o);
255 }
256
257 template <typename T, RawPtrTraits Traits>
UnsafeDanglingUntriaged(raw_ptr<T,Traits> && o)258 auto UnsafeDanglingUntriaged(raw_ptr<T, Traits>&& o) {
259 return internal::UnretainedWrapper<T, unretained_traits::MayDangleUntriaged,
260 Traits>(std::move(o));
261 }
262
263 template <typename T, RawPtrTraits Traits>
UnsafeDanglingUntriaged(const raw_ref<T,Traits> & o)264 auto UnsafeDanglingUntriaged(const raw_ref<T, Traits>& o) {
265 return internal::UnretainedRefWrapper<
266 T, unretained_traits::MayDangleUntriaged, Traits>(o);
267 }
268
269 template <typename T, RawPtrTraits Traits>
UnsafeDanglingUntriaged(raw_ref<T,Traits> && o)270 auto UnsafeDanglingUntriaged(raw_ref<T, Traits>&& o) {
271 return internal::UnretainedRefWrapper<
272 T, unretained_traits::MayDangleUntriaged, Traits>(std::move(o));
273 }
274
275 // RetainedRef() accepts a ref counted object and retains a reference to it.
276 // When the callback is called, the object is passed as a raw pointer.
277 //
278 // EXAMPLE OF RetainedRef():
279 //
280 // void foo(RefCountedBytes* bytes) {}
281 //
282 // scoped_refptr<RefCountedBytes> bytes = ...;
283 // OnceClosure callback = BindOnce(&foo, base::RetainedRef(bytes));
284 // std::move(callback).Run();
285 //
286 // Without RetainedRef, the scoped_refptr would try to implicitly convert to
287 // a raw pointer and fail compilation:
288 //
289 // OnceClosure callback = BindOnce(&foo, bytes); // ERROR!
290 template <typename T>
RetainedRef(T * o)291 inline internal::RetainedRefWrapper<T> RetainedRef(T* o) {
292 return internal::RetainedRefWrapper<T>(o);
293 }
294 template <typename T>
RetainedRef(scoped_refptr<T> o)295 inline internal::RetainedRefWrapper<T> RetainedRef(scoped_refptr<T> o) {
296 return internal::RetainedRefWrapper<T>(std::move(o));
297 }
298
299 // Owned() transfers ownership of an object to the callback resulting from
300 // bind; the object will be deleted when the callback is deleted.
301 //
302 // EXAMPLE OF Owned():
303 //
304 // void foo(int* arg) { cout << *arg << endl }
305 //
306 // int* pn = new int(1);
307 // RepeatingClosure foo_callback = BindRepeating(&foo, Owned(pn));
308 //
309 // foo_callback.Run(); // Prints "1"
310 // foo_callback.Run(); // Prints "1"
311 // *pn = 2;
312 // foo_callback.Run(); // Prints "2"
313 //
314 // foo_callback.Reset(); // |pn| is deleted. Also will happen when
315 // // |foo_callback| goes out of scope.
316 //
317 // Without Owned(), someone would have to know to delete |pn| when the last
318 // reference to the callback is deleted.
319 template <typename T>
Owned(T * o)320 inline internal::OwnedWrapper<T> Owned(T* o) {
321 return internal::OwnedWrapper<T>(o);
322 }
323
324 template <typename T, typename Deleter>
Owned(std::unique_ptr<T,Deleter> && ptr)325 inline internal::OwnedWrapper<T, Deleter> Owned(
326 std::unique_ptr<T, Deleter>&& ptr) {
327 return internal::OwnedWrapper<T, Deleter>(std::move(ptr));
328 }
329
330 // OwnedRef() stores an object in the callback resulting from
331 // bind and passes a reference to the object to the bound function.
332 //
333 // EXAMPLE OF OwnedRef():
334 //
335 // void foo(int& arg) { cout << ++arg << endl }
336 //
337 // int counter = 0;
338 // RepeatingClosure foo_callback = BindRepeating(&foo, OwnedRef(counter));
339 //
340 // foo_callback.Run(); // Prints "1"
341 // foo_callback.Run(); // Prints "2"
342 // foo_callback.Run(); // Prints "3"
343 //
344 // cout << counter; // Prints "0", OwnedRef creates a copy of counter.
345 //
346 // Supports OnceCallbacks as well, useful to pass placeholder arguments:
347 //
348 // void bar(int& ignore, const std::string& s) { cout << s << endl }
349 //
350 // OnceClosure bar_callback = BindOnce(&bar, OwnedRef(0), "Hello");
351 //
352 // std::move(bar_callback).Run(); // Prints "Hello"
353 //
354 // Without OwnedRef() it would not be possible to pass a mutable reference to an
355 // object owned by the callback.
356 template <typename T>
OwnedRef(T && t)357 internal::OwnedRefWrapper<std::decay_t<T>> OwnedRef(T&& t) {
358 return internal::OwnedRefWrapper<std::decay_t<T>>(std::forward<T>(t));
359 }
360
361 // Passed() is for transferring movable-but-not-copyable types (eg. unique_ptr)
362 // through a RepeatingCallback. Logically, this signifies a destructive transfer
363 // of the state of the argument into the target function. Invoking
364 // RepeatingCallback::Run() twice on a callback that was created with a Passed()
365 // argument will CHECK() because the first invocation would have already
366 // transferred ownership to the target function.
367 //
368 // Note that Passed() is not necessary with BindOnce(), as std::move() does the
369 // same thing. Avoid Passed() in favor of std::move() with BindOnce().
370 //
371 // EXAMPLE OF Passed():
372 //
373 // void TakesOwnership(std::unique_ptr<Foo> arg) { }
374 // std::unique_ptr<Foo> CreateFoo() { return std::make_unique<Foo>();
375 // }
376 //
377 // auto f = std::make_unique<Foo>();
378 //
379 // // |cb| is given ownership of Foo(). |f| is now NULL.
380 // // You can use std::move(f) in place of &f, but it's more verbose.
381 // RepeatingClosure cb = BindRepeating(&TakesOwnership, Passed(&f));
382 //
383 // // Run was never called so |cb| still owns Foo() and deletes
384 // // it on Reset().
385 // cb.Reset();
386 //
387 // // |cb| is given a new Foo created by CreateFoo().
388 // cb = BindRepeating(&TakesOwnership, Passed(CreateFoo()));
389 //
390 // // |arg| in TakesOwnership() is given ownership of Foo(). |cb|
391 // // no longer owns Foo() and, if reset, would not delete Foo().
392 // cb.Run(); // Foo() is now transferred to |arg| and deleted.
393 // cb.Run(); // This CHECK()s since Foo() already been used once.
394 //
395 // We offer 2 syntaxes for calling Passed(). The first takes an rvalue and is
396 // best suited for use with the return value of a function or other temporary
397 // rvalues. The second takes a pointer to the scoper and is just syntactic sugar
398 // to avoid having to write Passed(std::move(scoper)).
399 //
400 // Both versions of Passed() prevent T from being an lvalue reference. The first
401 // via use of enable_if, and the second takes a T* which will not bind to T&.
402 //
403 // DEPRECATED - Do not use in new code. See https://crbug.com/1326449
404 template <typename T>
405 requires(!std::is_lvalue_reference_v<T>)
Passed(T && scoper)406 inline internal::PassedWrapper<T> Passed(T&& scoper) {
407 return internal::PassedWrapper<T>(std::move(scoper));
408 }
409 template <typename T>
Passed(T * scoper)410 inline internal::PassedWrapper<T> Passed(T* scoper) {
411 return internal::PassedWrapper<T>(std::move(*scoper));
412 }
413
414 // IgnoreResult() is used to adapt a function or callback with a return type to
415 // one with a void return. This is most useful if you have a function with,
416 // say, a pesky ignorable bool return that you want to use with PostTask or
417 // something else that expect a callback with a void return.
418 //
419 // EXAMPLE OF IgnoreResult():
420 //
421 // int DoSomething(int arg) { cout << arg << endl; }
422 //
423 // // Assign to a callback with a void return type.
424 // OnceCallback<void(int)> cb = BindOnce(IgnoreResult(&DoSomething));
425 // std::move(cb).Run(1); // Prints "1".
426 //
427 // // Prints "2" on |ml|.
428 // ml->PostTask(FROM_HERE, BindOnce(IgnoreResult(&DoSomething), 2);
429 template <typename T>
IgnoreResult(T data)430 inline internal::IgnoreResultHelper<T> IgnoreResult(T data) {
431 return internal::IgnoreResultHelper<T>(std::move(data));
432 }
433
434 } // namespace base
435
436 #endif // BASE_FUNCTIONAL_BIND_H_
437