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.
4//
5// NOTE: Header files that do not require the full definition of Callback or
6// Closure should #include "base/callback_forward.h" instead of this file.
7
8#ifndef BASE_CALLBACK_H_
9#define BASE_CALLBACK_H_
10
11#include <stddef.h>
12
13#include "base/callback_forward.h"
14#include "base/callback_internal.h"
15
16// -----------------------------------------------------------------------------
17// Usage documentation
18// -----------------------------------------------------------------------------
19//
20// Overview:
21// A callback is similar in concept to a function pointer: it wraps a runnable
22// object such as a function, method, lambda, or even another callback, allowing
23// the runnable object to be invoked later via the callback object.
24//
25// Unlike function pointers, callbacks are created with base::BindOnce() or
26// base::BindRepeating() and support partial function application.
27//
28// A base::OnceCallback may be Run() at most once; a base::RepeatingCallback may
29// be Run() any number of times. |is_null()| is guaranteed to return true for a
30// moved-from callback.
31//
32// // The lambda takes two arguments, but the first argument |x| is bound at
33// // callback creation.
34// base::OnceCallback<int(int)> cb = base::BindOnce([] (int x, int y) {
35// return x + y;
36// }, 1);
37// // Run() only needs the remaining unbound argument |y|.
38// printf("1 + 2 = %d\n", std::move(cb).Run(2)); // Prints 3
39// printf("cb is null? %s\n",
40// cb.is_null() ? "true" : "false"); // Prints true
41// std::move(cb).Run(2); // Crashes since |cb| has already run.
42//
43// Callbacks also support cancellation. A common use is binding the receiver
44// object as a WeakPtr<T>. If that weak pointer is invalidated, calling Run()
45// will be a no-op. Note that |is_cancelled()| and |is_null()| are distinct:
46// simply cancelling a callback will not also make it null.
47//
48// base::Callback is currently a type alias for base::RepeatingCallback. In the
49// future, we expect to flip this to default to base::OnceCallback.
50//
51// See //docs/callback.md for the full documentation.
52
53namespace base {
54
55template <typename R, typename... Args>
56class OnceCallback<R(Args...)> : public internal::CallbackBase {
57 public:
58 using RunType = R(Args...);
59 using PolymorphicInvoke = R (*)(internal::BindStateBase*,
60 internal::PassingTraitsType<Args>...);
61
62 constexpr OnceCallback() = default;
63 OnceCallback(std::nullptr_t) = delete;
64
65 explicit OnceCallback(internal::BindStateBase* bind_state)
66 : internal::CallbackBase(bind_state) {}
67
68 OnceCallback(const OnceCallback&) = delete;
69 OnceCallback& operator=(const OnceCallback&) = delete;
70
71 OnceCallback(OnceCallback&&) noexcept = default;
72 OnceCallback& operator=(OnceCallback&&) noexcept = default;
73
74 OnceCallback(RepeatingCallback<RunType> other)
75 : internal::CallbackBase(std::move(other)) {}
76
77 OnceCallback& operator=(RepeatingCallback<RunType> other) {
78 static_cast<internal::CallbackBase&>(*this) = std::move(other);
79 return *this;
80 }
81
82 R Run(Args... args) const & {
83 static_assert(!sizeof(*this),
84 "OnceCallback::Run() may only be invoked on a non-const "
85 "rvalue, i.e. std::move(callback).Run().");
86 NOTREACHED();
87 }
88
89 R Run(Args... args) && {
90 // Move the callback instance into a local variable before the invocation,
91 // that ensures the internal state is cleared after the invocation.
92 // It's not safe to touch |this| after the invocation, since running the
93 // bound function may destroy |this|.
94 OnceCallback cb = std::move(*this);
95 PolymorphicInvoke f =
96 reinterpret_cast<PolymorphicInvoke>(cb.polymorphic_invoke());
97 return f(cb.bind_state_.get(), std::forward<Args>(args)...);
98 }
99};
100
101template <typename R, typename... Args>
102class RepeatingCallback<R(Args...)> : public internal::CallbackBaseCopyable {
103 public:
104 using RunType = R(Args...);
105 using PolymorphicInvoke = R (*)(internal::BindStateBase*,
106 internal::PassingTraitsType<Args>...);
107
108 constexpr RepeatingCallback() = default;
109 RepeatingCallback(std::nullptr_t) = delete;
110
111 explicit RepeatingCallback(internal::BindStateBase* bind_state)
112 : internal::CallbackBaseCopyable(bind_state) {}
113
114 // Copyable and movable.
115 RepeatingCallback(const RepeatingCallback&) = default;
116 RepeatingCallback& operator=(const RepeatingCallback&) = default;
117 RepeatingCallback(RepeatingCallback&&) noexcept = default;
118 RepeatingCallback& operator=(RepeatingCallback&&) noexcept = default;
119
120 bool operator==(const RepeatingCallback& other) const {
121 return EqualsInternal(other);
122 }
123
124 bool operator!=(const RepeatingCallback& other) const {
125 return !operator==(other);
126 }
127
128 // TODO(http://crbug.com/937566): Deprecated, use == or != instead.
129 bool Equals(const RepeatingCallback& other) const {
130 return EqualsInternal(other);
131 }
132
133 R Run(Args... args) const & {
134 PolymorphicInvoke f =
135 reinterpret_cast<PolymorphicInvoke>(this->polymorphic_invoke());
136 return f(this->bind_state_.get(), std::forward<Args>(args)...);
137 }
138
139 R Run(Args... args) && {
140 // Move the callback instance into a local variable before the invocation,
141 // that ensures the internal state is cleared after the invocation.
142 // It's not safe to touch |this| after the invocation, since running the
143 // bound function may destroy |this|.
144 RepeatingCallback cb = std::move(*this);
145 PolymorphicInvoke f =
146 reinterpret_cast<PolymorphicInvoke>(cb.polymorphic_invoke());
147 return f(cb.bind_state_.get(), std::forward<Args>(args)...);
148 }
149};
150
151} // namespace base
152
153#endif // BASE_CALLBACK_H_
154