blob: b0a82179a2310766914bee8c53d9ac4628769d40 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#ifndef WEBRTC_BASE_MESSAGEHANDLER_H_
12#define WEBRTC_BASE_MESSAGEHANDLER_H_
13
14#include "webrtc/base/constructormagic.h"
Jelena Marusic5d6e58e2015-07-13 11:16:39 +020015#include "webrtc/base/scoped_ptr.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000016
17namespace rtc {
18
19struct Message;
20
21// Messages get dispatched to a MessageHandler
22
23class MessageHandler {
24 public:
25 virtual ~MessageHandler();
26 virtual void OnMessage(Message* msg) = 0;
27
28 protected:
29 MessageHandler() {}
30
31 private:
32 DISALLOW_COPY_AND_ASSIGN(MessageHandler);
33};
34
35// Helper class to facilitate executing a functor on a thread.
36template <class ReturnT, class FunctorT>
37class FunctorMessageHandler : public MessageHandler {
38 public:
39 explicit FunctorMessageHandler(const FunctorT& functor)
40 : functor_(functor) {}
41 virtual void OnMessage(Message* msg) {
42 result_ = functor_();
43 }
44 const ReturnT& result() const { return result_; }
45
46 private:
47 FunctorT functor_;
48 ReturnT result_;
49};
50
Jelena Marusic5d6e58e2015-07-13 11:16:39 +020051// Specialization for rtc::scoped_ptr<ReturnT>.
52template <class ReturnT, class FunctorT>
53class FunctorMessageHandler<class rtc::scoped_ptr<ReturnT>, FunctorT>
54 : public MessageHandler {
55 public:
56 explicit FunctorMessageHandler(const FunctorT& functor) : functor_(functor) {}
57 virtual void OnMessage(Message* msg) { result_ = functor_().Pass(); }
58 rtc::scoped_ptr<ReturnT> result() { return result_.Pass(); }
59
60 private:
61 FunctorT functor_;
62 rtc::scoped_ptr<ReturnT> result_;
63};
64
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000065// Specialization for ReturnT of void.
66template <class FunctorT>
67class FunctorMessageHandler<void, FunctorT> : public MessageHandler {
68 public:
69 explicit FunctorMessageHandler(const FunctorT& functor)
70 : functor_(functor) {}
71 virtual void OnMessage(Message* msg) {
72 functor_();
73 }
74 void result() const {}
75
76 private:
77 FunctorT functor_;
78};
79
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000080} // namespace rtc
81
82#endif // WEBRTC_BASE_MESSAGEHANDLER_H_