1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
|
/*
* Copyright (C) 2011 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef WTF_Functional_h
#define WTF_Functional_h
#include "base/bind.h"
#include "base/threading/thread_checker.h"
#include "wtf/Allocator.h"
#include "wtf/Assertions.h"
#include "wtf/PassRefPtr.h"
#include "wtf/PtrUtil.h"
#include "wtf/RefPtr.h"
#include "wtf/ThreadSafeRefCounted.h"
#include "wtf/TypeTraits.h"
#include <utility>
namespace blink {
template <typename T>
class Member;
template <typename T>
class WeakMember;
}
namespace WTF {
// Functional.h provides a very simple way to bind a function pointer and
// arguments together into a function object that can be stored, copied and
// invoked, similar to boost::bind and std::bind in C++11.
// Thread Safety:
//
// WTF::bind() and WTF::Closure should be used for same-thread closures
// only, i.e. the closures must be created, executed and destructed on
// the same thread.
// Use crossThreadBind() and CrossThreadClosure if the function/task is called
// or destructed on a (potentially) different thread from the current thread.
// WTF::bind() and move semantics
// ==============================
//
// For unbound parameters (arguments supplied later on the bound functor
// directly), there are two ways to pass movable arguments:
//
// 1) Pass by rvalue reference.
//
// void yourFunction(Argument&& argument) { ... }
// std::unique_ptr<Function<void(Argument&&)>> functor =
// bind<Argument&&>(yourFunction);
//
// 2) Pass by value.
//
// void yourFunction(Argument argument) { ... }
// std::unique_ptr<Function<void(Argument)>> functor =
// bind<Argument>(yourFunction);
//
// Note that with the latter there will be *two* move constructions happening,
// because there needs to be at least one intermediary function call taking an
// argument of type "Argument" (i.e. passed by value). The former case does not
// require any move constructions inbetween.
//
// For bound parameters (arguments supplied on the creation of a functor), you
// can move your argument into the internal storage of the functor by supplying
// an rvalue to that argument (this is done in wrap() of ParamStorageTraits).
// However, to make the functor be able to get called multiple times, the
// stored object does not get moved out automatically when the underlying
// function is actually invoked. If you want to make an argument "auto-passed",
// you can do so by wrapping your bound argument with WTF::passed() function, as
// shown below:
//
// void yourFunction(Argument argument)
// {
// // |argument| is passed from the internal storage of functor.
// ...
// }
//
// ...
// std::unique_ptr<Function<void()>> functor = bind(yourFunction,
// WTF::passed(Argument()));
// ...
// (*functor)();
//
// The underlying function must receive the argument wrapped by WTF::passed() by
// rvalue reference or by value.
//
// Obviously, if you create a functor this way, you shouldn't call the functor
// twice or more; after the second call, the passed argument may be invalid.
enum FunctionThreadAffinity { CrossThreadAffinity, SameThreadAffinity };
template <typename T>
class PassedWrapper final {
public:
explicit PassedWrapper(T&& scoper) : m_scoper(std::move(scoper)) {}
PassedWrapper(PassedWrapper&& other) : m_scoper(std::move(other.m_scoper)) {}
T moveOut() const { return std::move(m_scoper); }
private:
mutable T m_scoper;
};
template <typename T>
PassedWrapper<T> passed(T&& value) {
static_assert(
!std::is_reference<T>::value,
"You must pass an rvalue to WTF::passed() so it can be moved. Add "
"std::move() if necessary.");
static_assert(!std::is_const<T>::value,
"|value| must not be const so it can be moved.");
return PassedWrapper<T>(std::move(value));
}
template <typename T, FunctionThreadAffinity threadAffinity>
class UnretainedWrapper final {
public:
explicit UnretainedWrapper(T* ptr) : m_ptr(ptr) {}
T* value() const { return m_ptr; }
private:
T* m_ptr;
};
template <typename T>
UnretainedWrapper<T, SameThreadAffinity> unretained(T* value) {
static_assert(!WTF::IsGarbageCollectedType<T>::value,
"WTF::unretained() + GCed type is forbidden");
return UnretainedWrapper<T, SameThreadAffinity>(value);
}
template <typename T>
UnretainedWrapper<T, CrossThreadAffinity> crossThreadUnretained(T* value) {
static_assert(!WTF::IsGarbageCollectedType<T>::value,
"crossThreadUnretained() + GCed type is forbidden");
return UnretainedWrapper<T, CrossThreadAffinity>(value);
}
template <typename T>
struct ParamStorageTraits {
typedef T StorageType;
static_assert(!std::is_pointer<T>::value,
"Raw pointers are not allowed to bind into WTF::Function. Wrap "
"it with either wrapPersistent, wrapWeakPersistent, "
"wrapCrossThreadPersistent, wrapCrossThreadWeakPersistent, "
"RefPtr or unretained.");
static_assert(!IsSubclassOfTemplate<T, blink::Member>::value &&
!IsSubclassOfTemplate<T, blink::WeakMember>::value,
"Member and WeakMember are not allowed to bind into "
"WTF::Function. Wrap it with either wrapPersistent, "
"wrapWeakPersistent, wrapCrossThreadPersistent or "
"wrapCrossThreadWeakPersistent.");
};
template <typename T>
struct ParamStorageTraits<PassRefPtr<T>> {
typedef RefPtr<T> StorageType;
};
template <typename T>
struct ParamStorageTraits<RefPtr<T>> {
typedef RefPtr<T> StorageType;
};
template <typename>
class RetainPtr;
template <typename T>
struct ParamStorageTraits<RetainPtr<T>> {
typedef RetainPtr<T> StorageType;
};
template <typename T>
struct ParamStorageTraits<PassedWrapper<T>> {
typedef PassedWrapper<T> StorageType;
};
template <typename T, FunctionThreadAffinity threadAffinity>
struct ParamStorageTraits<UnretainedWrapper<T, threadAffinity>> {
typedef UnretainedWrapper<T, threadAffinity> StorageType;
};
template <typename Signature,
FunctionThreadAffinity threadAffinity = SameThreadAffinity>
class Function;
template <typename R, typename... Args, FunctionThreadAffinity threadAffinity>
class Function<R(Args...), threadAffinity> {
USING_FAST_MALLOC(Function);
WTF_MAKE_NONCOPYABLE(Function);
public:
Function(base::Callback<R(Args...)> callback)
: m_callback(std::move(callback)) {}
~Function() { DCHECK(m_threadChecker.CalledOnValidThread()); }
R operator()(Args... args) {
DCHECK(m_threadChecker.CalledOnValidThread());
return m_callback.Run(std::forward<Args>(args)...);
}
bool isCancelled() const { return m_callback.IsCancelled(); }
friend base::Callback<R(Args...)> convertToBaseCallback(
std::unique_ptr<Function> function) {
if (function)
return std::move(function->m_callback);
return base::Callback<R(Args...)>();
}
private:
using MaybeThreadChecker =
typename std::conditional<threadAffinity == SameThreadAffinity,
base::ThreadChecker,
base::ThreadCheckerDoNothing>::type;
MaybeThreadChecker m_threadChecker;
base::Callback<R(Args...)> m_callback;
};
template <FunctionThreadAffinity threadAffinity,
typename FunctionType,
typename... BoundParameters>
std::unique_ptr<
Function<base::MakeUnboundRunType<FunctionType, BoundParameters...>,
threadAffinity>>
bindInternal(FunctionType function, BoundParameters&&... boundParameters) {
using UnboundRunType =
base::MakeUnboundRunType<FunctionType, BoundParameters...>;
return WTF::wrapUnique(new Function<UnboundRunType,
threadAffinity>(base::Bind(
function,
typename ParamStorageTraits<typename std::decay<BoundParameters>::type>::
StorageType(std::forward<BoundParameters>(boundParameters))...)));
}
template <typename FunctionType, typename... BoundParameters>
std::unique_ptr<
Function<base::MakeUnboundRunType<FunctionType, BoundParameters...>,
SameThreadAffinity>>
bind(FunctionType function, BoundParameters&&... boundParameters) {
return bindInternal<SameThreadAffinity>(
function, std::forward<BoundParameters>(boundParameters)...);
}
typedef Function<void(), SameThreadAffinity> Closure;
typedef Function<void(), CrossThreadAffinity> CrossThreadClosure;
} // namespace WTF
namespace base {
template <typename T>
struct BindUnwrapTraits<WTF::RefPtr<T>> {
static T* Unwrap(const WTF::RefPtr<T>& wrapped) { return wrapped.get(); }
};
template <typename T>
struct BindUnwrapTraits<WTF::PassedWrapper<T>> {
static T Unwrap(const WTF::PassedWrapper<T>& wrapped) {
return wrapped.moveOut();
}
};
template <typename T, WTF::FunctionThreadAffinity threadAffinity>
struct BindUnwrapTraits<WTF::UnretainedWrapper<T, threadAffinity>> {
static T* Unwrap(const WTF::UnretainedWrapper<T, threadAffinity>& wrapped) {
return wrapped.value();
}
};
} // namespace base
using WTF::crossThreadUnretained;
using WTF::Function;
using WTF::CrossThreadClosure;
#endif // WTF_Functional_h
|