blob: 983659484ea351d547107fee466b8d9fbf21a772 [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
Steve Anton10542f22019-01-11 09:11:00 -080011#ifndef RTC_BASE_MESSAGE_HANDLER_H_
12#define RTC_BASE_MESSAGE_HANDLER_H_
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020014#include <utility>
kwiberg0eb15ed2015-12-17 03:04:15 -080015
Steve Anton10542f22019-01-11 09:11:00 -080016#include "rtc_base/constructor_magic.h"
Mirko Bonadei35214fc2019-09-23 14:54:28 +020017#include "rtc_base/system/rtc_export.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020018
19namespace rtc {
20
21struct Message;
22
23// Messages get dispatched to a MessageHandler
24
Mirko Bonadei35214fc2019-09-23 14:54:28 +020025class RTC_EXPORT MessageHandler {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020026 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 23:01:06 +020041 explicit FunctorMessageHandler(FunctorT&& functor)
42 : functor_(std::forward<FunctorT>(functor)) {}
Yves Gerey665174f2018-06-19 15:03:05 +020043 virtual void OnMessage(Message* msg) { result_ = functor_(); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020044 const ReturnT& result() const { return result_; }
45
46 // Returns moved result. Should not call result() or MoveResult() again
47 // after this.
48 ReturnT MoveResult() { return std::move(result_); }
49
50 private:
51 FunctorT functor_;
52 ReturnT result_;
53};
54
55// Specialization for ReturnT of void.
56template <class FunctorT>
57class FunctorMessageHandler<void, FunctorT> : public MessageHandler {
58 public:
Artem Titovd8bd7502019-01-09 21:10:00 +010059 explicit FunctorMessageHandler(FunctorT&& functor)
60 : functor_(std::forward<FunctorT>(functor)) {}
Yves Gerey665174f2018-06-19 15:03:05 +020061 virtual void OnMessage(Message* msg) { functor_(); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020062 void result() const {}
63 void MoveResult() {}
64
65 private:
66 FunctorT functor_;
67};
68
Yves Gerey665174f2018-06-19 15:03:05 +020069} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000070
Steve Anton10542f22019-01-11 09:11:00 -080071#endif // RTC_BASE_MESSAGE_HANDLER_H_