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// This file contains utility functions and classes that help the
6// implementation, and management of the Callback objects.
7
8#ifndef BASE_CALLBACK_INTERNAL_H_
9#define BASE_CALLBACK_INTERNAL_H_
10
11#include <stddef.h>
12
13#include "base/base_export.h"
14#include "base/memory/ref_counted.h"
15#include "base/memory/scoped_ptr.h"
16
17template <typename T>
18class ScopedVector;
19
20namespace base {
21namespace internal {
22
23// BindStateBase is used to provide an opaque handle that the Callback
24// class can use to represent a function object with bound arguments.  It
25// behaves as an existential type that is used by a corresponding
26// DoInvoke function to perform the function execution.  This allows
27// us to shield the Callback class from the types of the bound argument via
28// "type erasure."
29class BindStateBase : public RefCountedThreadSafe<BindStateBase> {
30 protected:
31  friend class RefCountedThreadSafe<BindStateBase>;
32  virtual ~BindStateBase() {}
33};
34
35// Holds the Callback methods that don't require specialization to reduce
36// template bloat.
37class BASE_EXPORT CallbackBase {
38 public:
39  // Returns true if Callback is null (doesn't refer to anything).
40  bool is_null() const;
41
42  // Returns the Callback into an uninitialized state.
43  void Reset();
44
45 protected:
46  // In C++, it is safe to cast function pointers to function pointers of
47  // another type. It is not okay to use void*. We create a InvokeFuncStorage
48  // that that can store our function pointer, and then cast it back to
49  // the original type on usage.
50  typedef void(*InvokeFuncStorage)(void);
51
52  // Returns true if this callback equals |other|. |other| may be null.
53  bool Equals(const CallbackBase& other) const;
54
55  // Allow initializing of |bind_state_| via the constructor to avoid default
56  // initialization of the scoped_refptr.  We do not also initialize
57  // |polymorphic_invoke_| here because doing a normal assignment in the
58  // derived Callback templates makes for much nicer compiler errors.
59  explicit CallbackBase(BindStateBase* bind_state);
60
61  // Force the destructor to be instantiated inside this translation unit so
62  // that our subclasses will not get inlined versions.  Avoids more template
63  // bloat.
64  ~CallbackBase();
65
66  scoped_refptr<BindStateBase> bind_state_;
67  InvokeFuncStorage polymorphic_invoke_;
68};
69
70// A helper template to determine if given type is non-const move-only-type,
71// i.e. if a value of the given type should be passed via .Pass() in a
72// destructive way.
73template <typename T> struct IsMoveOnlyType {
74  template <typename U>
75  static YesType Test(const typename U::MoveOnlyTypeForCPP03*);
76
77  template <typename U>
78  static NoType Test(...);
79
80  static const bool value = sizeof(Test<T>(0)) == sizeof(YesType) &&
81                            !is_const<T>::value;
82};
83
84// This is a typetraits object that's used to take an argument type, and
85// extract a suitable type for storing and forwarding arguments.
86//
87// In particular, it strips off references, and converts arrays to
88// pointers for storage; and it avoids accidentally trying to create a
89// "reference of a reference" if the argument is a reference type.
90//
91// This array type becomes an issue for storage because we are passing bound
92// parameters by const reference. In this case, we end up passing an actual
93// array type in the initializer list which C++ does not allow.  This will
94// break passing of C-string literals.
95template <typename T, bool is_move_only = IsMoveOnlyType<T>::value>
96struct CallbackParamTraits {
97  typedef const T& ForwardType;
98  typedef T StorageType;
99};
100
101// The Storage should almost be impossible to trigger unless someone manually
102// specifies type of the bind parameters.  However, in case they do,
103// this will guard against us accidentally storing a reference parameter.
104//
105// The ForwardType should only be used for unbound arguments.
106template <typename T>
107struct CallbackParamTraits<T&, false> {
108  typedef T& ForwardType;
109  typedef T StorageType;
110};
111
112// Note that for array types, we implicitly add a const in the conversion. This
113// means that it is not possible to bind array arguments to functions that take
114// a non-const pointer. Trying to specialize the template based on a "const
115// T[n]" does not seem to match correctly, so we are stuck with this
116// restriction.
117template <typename T, size_t n>
118struct CallbackParamTraits<T[n], false> {
119  typedef const T* ForwardType;
120  typedef const T* StorageType;
121};
122
123// See comment for CallbackParamTraits<T[n]>.
124template <typename T>
125struct CallbackParamTraits<T[], false> {
126  typedef const T* ForwardType;
127  typedef const T* StorageType;
128};
129
130// Parameter traits for movable-but-not-copyable scopers.
131//
132// Callback<>/Bind() understands movable-but-not-copyable semantics where
133// the type cannot be copied but can still have its state destructively
134// transferred (aka. moved) to another instance of the same type by calling a
135// helper function.  When used with Bind(), this signifies transferal of the
136// object's state to the target function.
137//
138// For these types, the ForwardType must not be a const reference, or a
139// reference.  A const reference is inappropriate, and would break const
140// correctness, because we are implementing a destructive move.  A non-const
141// reference cannot be used with temporaries which means the result of a
142// function or a cast would not be usable with Callback<> or Bind().
143template <typename T>
144struct CallbackParamTraits<T, true> {
145  typedef T ForwardType;
146  typedef T StorageType;
147};
148
149// CallbackForward() is a very limited simulation of C++11's std::forward()
150// used by the Callback/Bind system for a set of movable-but-not-copyable
151// types.  It is needed because forwarding a movable-but-not-copyable
152// argument to another function requires us to invoke the proper move
153// operator to create a rvalue version of the type.  The supported types are
154// whitelisted below as overloads of the CallbackForward() function. The
155// default template compiles out to be a no-op.
156//
157// In C++11, std::forward would replace all uses of this function.  However, it
158// is impossible to implement a general std::forward with C++11 due to a lack
159// of rvalue references.
160//
161// In addition to Callback/Bind, this is used by PostTaskAndReplyWithResult to
162// simulate std::forward() and forward the result of one Callback as a
163// parameter to another callback. This is to support Callbacks that return
164// the movable-but-not-copyable types whitelisted above.
165template <typename T>
166typename enable_if<!IsMoveOnlyType<T>::value, T>::type& CallbackForward(T& t) {
167  return t;
168}
169
170template <typename T>
171typename enable_if<IsMoveOnlyType<T>::value, T>::type CallbackForward(T& t) {
172  return t.Pass();
173}
174
175}  // namespace internal
176}  // namespace base
177
178#endif  // BASE_CALLBACK_INTERNAL_H_
179