blob: ff953f7898d484dda02ba3b84d43cc07e47d1add [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:261/*
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
Mirko Bonadei92ea95e2017-09-15 04:47:3111#ifndef RTC_BASE_MESSAGEHANDLER_H_
12#define RTC_BASE_MESSAGEHANDLER_H_
henrike@webrtc.orgf0488722014-05-13 18:00:2613
Henrik Kjellanderec78f1c2017-06-29 05:52:5014#include <memory>
15#include <utility>
kwiberg0eb15ed2015-12-17 11:04:1516
Mirko Bonadei92ea95e2017-09-15 04:47:3117#include "rtc_base/constructormagic.h"
Henrik Kjellanderec78f1c2017-06-29 05:52:5018
19namespace rtc {
20
21struct Message;
22
23// Messages get dispatched to a MessageHandler
24
25class MessageHandler {
26 public:
27 virtual ~MessageHandler();
28 virtual void OnMessage(Message* msg) = 0;
29
30 protected:
31 MessageHandler() {}
32
33 private:
34 RTC_DISALLOW_COPY_AND_ASSIGN(MessageHandler);
35};
36
37// Helper class to facilitate executing a functor on a thread.
38template <class ReturnT, class FunctorT>
39class FunctorMessageHandler : public MessageHandler {
40 public:
Karl Wibergd6b48192017-10-16 21:01:0641 explicit FunctorMessageHandler(FunctorT&& functor)
42 : functor_(std::forward<FunctorT>(functor)) {}
Henrik Kjellanderec78f1c2017-06-29 05:52:5043 virtual void OnMessage(Message* msg) {
44 result_ = functor_();
45 }
46 const ReturnT& result() const { return result_; }
47
48 // Returns moved result. Should not call result() or MoveResult() again
49 // after this.
50 ReturnT MoveResult() { return std::move(result_); }
51
52 private:
53 FunctorT functor_;
54 ReturnT result_;
55};
56
57// Specialization for ReturnT of void.
58template <class FunctorT>
59class FunctorMessageHandler<void, FunctorT> : public MessageHandler {
60 public:
61 explicit FunctorMessageHandler(const FunctorT& functor)
62 : functor_(functor) {}
63 virtual void OnMessage(Message* msg) {
64 functor_();
65 }
66 void result() const {}
67 void MoveResult() {}
68
69 private:
70 FunctorT functor_;
71};
72
73} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:2674
Mirko Bonadei92ea95e2017-09-15 04:47:3175#endif // RTC_BASE_MESSAGEHANDLER_H_