• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifndef BASE_TASK_RUNNER_UTIL_H_
6 #define BASE_TASK_RUNNER_UTIL_H_
7 
8 #include "base/bind.h"
9 #include "base/bind_helpers.h"
10 #include "base/logging.h"
11 #include "base/task_runner.h"
12 
13 namespace base {
14 
15 namespace internal {
16 
17 // Adapts a function that produces a result via a return value to
18 // one that returns via an output parameter.
19 template <typename ReturnType>
ReturnAsParamAdapter(const Callback<ReturnType (void)> & func,ReturnType * result)20 void ReturnAsParamAdapter(const Callback<ReturnType(void)>& func,
21                           ReturnType* result) {
22   *result = func.Run();
23 }
24 
25 // Adapts a T* result to a callblack that expects a T.
26 template <typename TaskReturnType, typename ReplyArgType>
ReplyAdapter(const Callback<void (ReplyArgType)> & callback,TaskReturnType * result)27 void ReplyAdapter(const Callback<void(ReplyArgType)>& callback,
28                   TaskReturnType* result) {
29   // TODO(ajwong): Remove this conditional and add a DCHECK to enforce that
30   // |reply| must be non-null in PostTaskAndReplyWithResult() below after
31   // current code that relies on this API softness has been removed.
32   // http://crbug.com/162712
33   if (!callback.is_null())
34     callback.Run(std::move(*result));
35 }
36 
37 }  // namespace internal
38 
39 // When you have these methods
40 //
41 //   R DoWorkAndReturn();
42 //   void Callback(const R& result);
43 //
44 // and want to call them in a PostTaskAndReply kind of fashion where the
45 // result of DoWorkAndReturn is passed to the Callback, you can use
46 // PostTaskAndReplyWithResult as in this example:
47 //
48 // PostTaskAndReplyWithResult(
49 //     target_thread_.task_runner(),
50 //     FROM_HERE,
51 //     Bind(&DoWorkAndReturn),
52 //     Bind(&Callback));
53 template <typename TaskReturnType, typename ReplyArgType>
PostTaskAndReplyWithResult(TaskRunner * task_runner,const tracked_objects::Location & from_here,const Callback<TaskReturnType (void)> & task,const Callback<void (ReplyArgType)> & reply)54 bool PostTaskAndReplyWithResult(
55     TaskRunner* task_runner,
56     const tracked_objects::Location& from_here,
57     const Callback<TaskReturnType(void)>& task,
58     const Callback<void(ReplyArgType)>& reply) {
59   TaskReturnType* result = new TaskReturnType();
60   return task_runner->PostTaskAndReply(
61       from_here,
62       base::Bind(&internal::ReturnAsParamAdapter<TaskReturnType>, task,
63                  result),
64       base::Bind(&internal::ReplyAdapter<TaskReturnType, ReplyArgType>, reply,
65                  base::Owned(result)));
66 }
67 
68 }  // namespace base
69 
70 #endif  // BASE_TASK_RUNNER_UTIL_H_
71