Port Android relocation packer to chromium build
[chromium-blink-merge.git] / base / callback.h
blob00669dd83d1c2dbb518134f0243fd5dbec104133
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 #ifndef BASE_CALLBACK_H_
6 #define BASE_CALLBACK_H_
8 #include "base/callback_forward.h"
9 #include "base/callback_internal.h"
10 #include "base/template_util.h"
12 // NOTE: Header files that do not require the full definition of Callback or
13 // Closure should #include "base/callback_forward.h" instead of this file.
15 // -----------------------------------------------------------------------------
16 // Introduction
17 // -----------------------------------------------------------------------------
19 // The templated Callback class is a generalized function object. Together
20 // with the Bind() function in bind.h, they provide a type-safe method for
21 // performing partial application of functions.
23 // Partial application (or "currying") is the process of binding a subset of
24 // a function's arguments to produce another function that takes fewer
25 // arguments. This can be used to pass around a unit of delayed execution,
26 // much like lexical closures are used in other languages. For example, it
27 // is used in Chromium code to schedule tasks on different MessageLoops.
29 // A callback with no unbound input parameters (base::Callback<void(void)>)
30 // is called a base::Closure. Note that this is NOT the same as what other
31 // languages refer to as a closure -- it does not retain a reference to its
32 // enclosing environment.
34 // MEMORY MANAGEMENT AND PASSING
36 // The Callback objects themselves should be passed by const-reference, and
37 // stored by copy. They internally store their state via a refcounted class
38 // and thus do not need to be deleted.
40 // The reason to pass via a const-reference is to avoid unnecessary
41 // AddRef/Release pairs to the internal state.
44 // -----------------------------------------------------------------------------
45 // Quick reference for basic stuff
46 // -----------------------------------------------------------------------------
48 // BINDING A BARE FUNCTION
50 // int Return5() { return 5; }
51 // base::Callback<int(void)> func_cb = base::Bind(&Return5);
52 // LOG(INFO) << func_cb.Run(); // Prints 5.
54 // BINDING A CLASS METHOD
56 // The first argument to bind is the member function to call, the second is
57 // the object on which to call it.
59 // class Ref : public base::RefCountedThreadSafe<Ref> {
60 // public:
61 // int Foo() { return 3; }
62 // void PrintBye() { LOG(INFO) << "bye."; }
63 // };
64 // scoped_refptr<Ref> ref = new Ref();
65 // base::Callback<void(void)> ref_cb = base::Bind(&Ref::Foo, ref);
66 // LOG(INFO) << ref_cb.Run(); // Prints out 3.
68 // By default the object must support RefCounted or you will get a compiler
69 // error. If you're passing between threads, be sure it's
70 // RefCountedThreadSafe! See "Advanced binding of member functions" below if
71 // you don't want to use reference counting.
73 // RUNNING A CALLBACK
75 // Callbacks can be run with their "Run" method, which has the same
76 // signature as the template argument to the callback.
78 // void DoSomething(const base::Callback<void(int, std::string)>& callback) {
79 // callback.Run(5, "hello");
80 // }
82 // Callbacks can be run more than once (they don't get deleted or marked when
83 // run). However, this precludes using base::Passed (see below).
85 // void DoSomething(const base::Callback<double(double)>& callback) {
86 // double myresult = callback.Run(3.14159);
87 // myresult += callback.Run(2.71828);
88 // }
90 // PASSING UNBOUND INPUT PARAMETERS
92 // Unbound parameters are specified at the time a callback is Run(). They are
93 // specified in the Callback template type:
95 // void MyFunc(int i, const std::string& str) {}
96 // base::Callback<void(int, const std::string&)> cb = base::Bind(&MyFunc);
97 // cb.Run(23, "hello, world");
99 // PASSING BOUND INPUT PARAMETERS
101 // Bound parameters are specified when you create thee callback as arguments
102 // to Bind(). They will be passed to the function and the Run()ner of the
103 // callback doesn't see those values or even know that the function it's
104 // calling.
106 // void MyFunc(int i, const std::string& str) {}
107 // base::Callback<void(void)> cb = base::Bind(&MyFunc, 23, "hello world");
108 // cb.Run();
110 // A callback with no unbound input parameters (base::Callback<void(void)>)
111 // is called a base::Closure. So we could have also written:
113 // base::Closure cb = base::Bind(&MyFunc, 23, "hello world");
115 // When calling member functions, bound parameters just go after the object
116 // pointer.
118 // base::Closure cb = base::Bind(&MyClass::MyFunc, this, 23, "hello world");
120 // PARTIAL BINDING OF PARAMETERS
122 // You can specify some parameters when you create the callback, and specify
123 // the rest when you execute the callback.
125 // void MyFunc(int i, const std::string& str) {}
126 // base::Callback<void(const std::string&)> cb = base::Bind(&MyFunc, 23);
127 // cb.Run("hello world");
129 // When calling a function bound parameters are first, followed by unbound
130 // parameters.
133 // -----------------------------------------------------------------------------
134 // Quick reference for advanced binding
135 // -----------------------------------------------------------------------------
137 // BINDING A CLASS METHOD WITH WEAK POINTERS
139 // base::Bind(&MyClass::Foo, GetWeakPtr());
141 // The callback will not be run if the object has already been destroyed.
142 // DANGER: weak pointers are not threadsafe, so don't use this
143 // when passing between threads!
145 // BINDING A CLASS METHOD WITH MANUAL LIFETIME MANAGEMENT
147 // base::Bind(&MyClass::Foo, base::Unretained(this));
149 // This disables all lifetime management on the object. You're responsible
150 // for making sure the object is alive at the time of the call. You break it,
151 // you own it!
153 // BINDING A CLASS METHOD AND HAVING THE CALLBACK OWN THE CLASS
155 // MyClass* myclass = new MyClass;
156 // base::Bind(&MyClass::Foo, base::Owned(myclass));
158 // The object will be deleted when the callback is destroyed, even if it's
159 // not run (like if you post a task during shutdown). Potentially useful for
160 // "fire and forget" cases.
162 // IGNORING RETURN VALUES
164 // Sometimes you want to call a function that returns a value in a callback
165 // that doesn't expect a return value.
167 // int DoSomething(int arg) { cout << arg << endl; }
168 // base::Callback<void<int>) cb =
169 // base::Bind(base::IgnoreResult(&DoSomething));
172 // -----------------------------------------------------------------------------
173 // Quick reference for binding parameters to Bind()
174 // -----------------------------------------------------------------------------
176 // Bound parameters are specified as arguments to Bind() and are passed to the
177 // function. A callback with no parameters or no unbound parameters is called a
178 // Closure (base::Callback<void(void)> and base::Closure are the same thing).
180 // PASSING PARAMETERS OWNED BY THE CALLBACK
182 // void Foo(int* arg) { cout << *arg << endl; }
183 // int* pn = new int(1);
184 // base::Closure foo_callback = base::Bind(&foo, base::Owned(pn));
186 // The parameter will be deleted when the callback is destroyed, even if it's
187 // not run (like if you post a task during shutdown).
189 // PASSING PARAMETERS AS A scoped_ptr
191 // void TakesOwnership(scoped_ptr<Foo> arg) {}
192 // scoped_ptr<Foo> f(new Foo);
193 // // f becomes null during the following call.
194 // base::Closure cb = base::Bind(&TakesOwnership, base::Passed(&f));
196 // Ownership of the parameter will be with the callback until the it is run,
197 // when ownership is passed to the callback function. This means the callback
198 // can only be run once. If the callback is never run, it will delete the
199 // object when it's destroyed.
201 // PASSING PARAMETERS AS A scoped_refptr
203 // void TakesOneRef(scoped_refptr<Foo> arg) {}
204 // scoped_refptr<Foo> f(new Foo)
205 // base::Closure cb = base::Bind(&TakesOneRef, f);
207 // This should "just work." The closure will take a reference as long as it
208 // is alive, and another reference will be taken for the called function.
210 // PASSING PARAMETERS BY REFERENCE
212 // Const references are *copied* unless ConstRef is used. Example:
214 // void foo(const int& arg) { printf("%d %p\n", arg, &arg); }
215 // int n = 1;
216 // base::Closure has_copy = base::Bind(&foo, n);
217 // base::Closure has_ref = base::Bind(&foo, base::ConstRef(n));
218 // n = 2;
219 // foo(n); // Prints "2 0xaaaaaaaaaaaa"
220 // has_copy.Run(); // Prints "1 0xbbbbbbbbbbbb"
221 // has_ref.Run(); // Prints "2 0xaaaaaaaaaaaa"
223 // Normally parameters are copied in the closure. DANGER: ConstRef stores a
224 // const reference instead, referencing the original parameter. This means
225 // that you must ensure the object outlives the callback!
228 // -----------------------------------------------------------------------------
229 // Implementation notes
230 // -----------------------------------------------------------------------------
232 // WHERE IS THIS DESIGN FROM:
234 // The design Callback and Bind is heavily influenced by C++'s
235 // tr1::function/tr1::bind, and by the "Google Callback" system used inside
236 // Google.
239 // HOW THE IMPLEMENTATION WORKS:
241 // There are three main components to the system:
242 // 1) The Callback classes.
243 // 2) The Bind() functions.
244 // 3) The arguments wrappers (e.g., Unretained() and ConstRef()).
246 // The Callback classes represent a generic function pointer. Internally,
247 // it stores a refcounted piece of state that represents the target function
248 // and all its bound parameters. Each Callback specialization has a templated
249 // constructor that takes an BindState<>*. In the context of the constructor,
250 // the static type of this BindState<> pointer uniquely identifies the
251 // function it is representing, all its bound parameters, and a Run() method
252 // that is capable of invoking the target.
254 // Callback's constructor takes the BindState<>* that has the full static type
255 // and erases the target function type as well as the types of the bound
256 // parameters. It does this by storing a pointer to the specific Run()
257 // function, and upcasting the state of BindState<>* to a
258 // BindStateBase*. This is safe as long as this BindStateBase pointer
259 // is only used with the stored Run() pointer.
261 // To BindState<> objects are created inside the Bind() functions.
262 // These functions, along with a set of internal templates, are responsible for
264 // - Unwrapping the function signature into return type, and parameters
265 // - Determining the number of parameters that are bound
266 // - Creating the BindState storing the bound parameters
267 // - Performing compile-time asserts to avoid error-prone behavior
268 // - Returning an Callback<> with an arity matching the number of unbound
269 // parameters and that knows the correct refcounting semantics for the
270 // target object if we are binding a method.
272 // The Bind functions do the above using type-inference, and template
273 // specializations.
275 // By default Bind() will store copies of all bound parameters, and attempt
276 // to refcount a target object if the function being bound is a class method.
277 // These copies are created even if the function takes parameters as const
278 // references. (Binding to non-const references is forbidden, see bind.h.)
280 // To change this behavior, we introduce a set of argument wrappers
281 // (e.g., Unretained(), and ConstRef()). These are simple container templates
282 // that are passed by value, and wrap a pointer to argument. See the
283 // file-level comment in base/bind_helpers.h for more info.
285 // These types are passed to the Unwrap() functions, and the MaybeRefcount()
286 // functions respectively to modify the behavior of Bind(). The Unwrap()
287 // and MaybeRefcount() functions change behavior by doing partial
288 // specialization based on whether or not a parameter is a wrapper type.
290 // ConstRef() is similar to tr1::cref. Unretained() is specific to Chromium.
293 // WHY NOT TR1 FUNCTION/BIND?
295 // Direct use of tr1::function and tr1::bind was considered, but ultimately
296 // rejected because of the number of copy constructors invocations involved
297 // in the binding of arguments during construction, and the forwarding of
298 // arguments during invocation. These copies will no longer be an issue in
299 // C++0x because C++0x will support rvalue reference allowing for the compiler
300 // to avoid these copies. However, waiting for C++0x is not an option.
302 // Measured with valgrind on gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5), the
303 // tr1::bind call itself will invoke a non-trivial copy constructor three times
304 // for each bound parameter. Also, each when passing a tr1::function, each
305 // bound argument will be copied again.
307 // In addition to the copies taken at binding and invocation, copying a
308 // tr1::function causes a copy to be made of all the bound parameters and
309 // state.
311 // Furthermore, in Chromium, it is desirable for the Callback to take a
312 // reference on a target object when representing a class method call. This
313 // is not supported by tr1.
315 // Lastly, tr1::function and tr1::bind has a more general and flexible API.
316 // This includes things like argument reordering by use of
317 // tr1::bind::placeholder, support for non-const reference parameters, and some
318 // limited amount of subtyping of the tr1::function object (e.g.,
319 // tr1::function<int(int)> is convertible to tr1::function<void(int)>).
321 // These are not features that are required in Chromium. Some of them, such as
322 // allowing for reference parameters, and subtyping of functions, may actually
323 // become a source of errors. Removing support for these features actually
324 // allows for a simpler implementation, and a terser Currying API.
327 // WHY NOT GOOGLE CALLBACKS?
329 // The Google callback system also does not support refcounting. Furthermore,
330 // its implementation has a number of strange edge cases with respect to type
331 // conversion of its arguments. In particular, the argument's constness must
332 // at times match exactly the function signature, or the type-inference might
333 // break. Given the above, writing a custom solution was easier.
336 // MISSING FUNCTIONALITY
337 // - Invoking the return of Bind. Bind(&foo).Run() does not work;
338 // - Binding arrays to functions that take a non-const pointer.
339 // Example:
340 // void Foo(const char* ptr);
341 // void Bar(char* ptr);
342 // Bind(&Foo, "test");
343 // Bind(&Bar, "test"); // This fails because ptr is not const.
345 namespace base {
347 // First, we forward declare the Callback class template. This informs the
348 // compiler that the template only has 1 type parameter which is the function
349 // signature that the Callback is representing.
351 // After this, create template specializations for 0-7 parameters. Note that
352 // even though the template typelist grows, the specialization still
353 // only has one type: the function signature.
355 // If you are thinking of forward declaring Callback in your own header file,
356 // please include "base/callback_forward.h" instead.
357 template <typename Sig>
358 class Callback;
360 namespace internal {
361 template <typename Runnable, typename RunType, typename BoundArgsType>
362 struct BindState;
363 } // namespace internal
365 template <typename R, typename... Args>
366 class Callback<R(Args...)> : public internal::CallbackBase {
367 public:
368 typedef R(RunType)(Args...);
370 Callback() : CallbackBase(NULL) { }
372 // Note that this constructor CANNOT be explicit, and that Bind() CANNOT
373 // return the exact Callback<> type. See base/bind.h for details.
374 template <typename Runnable, typename BindRunType, typename BoundArgsType>
375 Callback(internal::BindState<Runnable, BindRunType,
376 BoundArgsType>* bind_state)
377 : CallbackBase(bind_state) {
378 // Force the assignment to a local variable of PolymorphicInvoke
379 // so the compiler will typecheck that the passed in Run() method has
380 // the correct type.
381 PolymorphicInvoke invoke_func =
382 &internal::BindState<Runnable, BindRunType, BoundArgsType>
383 ::InvokerType::Run;
384 polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
387 bool Equals(const Callback& other) const {
388 return CallbackBase::Equals(other);
391 R Run(typename internal::CallbackParamTraits<Args>::ForwardType... args)
392 const {
393 PolymorphicInvoke f =
394 reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);
396 return f(bind_state_.get(), internal::CallbackForward(args)...);
399 private:
400 typedef R(*PolymorphicInvoke)(
401 internal::BindStateBase*,
402 typename internal::CallbackParamTraits<Args>::ForwardType...);
405 // Syntactic sugar to make Callback<void(void)> easier to declare since it
406 // will be used in a lot of APIs with delayed execution.
407 typedef Callback<void(void)> Closure;
409 } // namespace base
411 #endif // BASE_CALLBACK_H_