1 // Copyright (c) 2015 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 MEDIA_BASE_BIND_TO_CURRENT_LOOP_H_
6 #define MEDIA_BASE_BIND_TO_CURRENT_LOOP_H_
9 #include "base/location.h"
10 #include "base/message_loop/message_loop_proxy.h"
11 #include "base/single_thread_task_runner.h"
13 // This is a helper utility for base::Bind()ing callbacks to the current
14 // MessageLoop. The typical use is when |a| (of class |A|) wants to hand a
15 // callback such as base::Bind(&A::AMethod, a) to |b|, but needs to ensure that
16 // when |b| executes the callback, it does so on |a|'s current MessageLoop.
18 // Typical usage: request to be called back on the current thread:
19 // other->StartAsyncProcessAndCallMeBack(
20 // media::BindToCurrentLoop(base::Bind(&MyClass::MyMethod, this)));
22 // Note that like base::Bind(), BindToCurrentLoop() can't bind non-constant
23 // references, and that *unlike* base::Bind(), BindToCurrentLoop() makes copies
24 // of its arguments, and thus can't be used with arrays.
28 // Mimic base::internal::CallbackForward, replacing p.Pass() with
29 // base::Passed(&p) to account for the extra layer of indirection.
32 T
& TrampolineForward(T
& t
) { return t
; }
34 template <typename T
, typename R
>
35 base::internal::PassedWrapper
<scoped_ptr
<T
, R
> > TrampolineForward(
36 scoped_ptr
<T
, R
>& p
) { return base::Passed(&p
); }
39 base::internal::PassedWrapper
<ScopedVector
<T
> > TrampolineForward(
40 ScopedVector
<T
>& p
) { return base::Passed(&p
); }
42 // First, tell the compiler TrampolineHelper is a struct template with one
43 // type parameter. Then define specializations where the type is a function
44 // returning void and taking zero or more arguments.
45 template <typename Sig
> struct TrampolineHelper
;
47 template <typename
... Args
>
48 struct TrampolineHelper
<void(Args
...)> {
50 const scoped_refptr
<base::SingleThreadTaskRunner
>& task_runner
,
51 const base::Callback
<void(Args
...)>& cb
,
53 task_runner
->PostTask(FROM_HERE
,
54 base::Bind(cb
, TrampolineForward(args
)...));
58 } // namespace internal
61 static base::Callback
<T
> BindToCurrentLoop(
62 const base::Callback
<T
>& cb
) {
63 return base::Bind(&internal::TrampolineHelper
<T
>::Run
,
64 base::MessageLoopProxy::current(), cb
);
69 #endif // MEDIA_BASE_BIND_TO_CURRENT_LOOP_H_