Line data Source code
1 : /* Loosely-coupled notifications via the Publish-Subscribe pattern.
2 : Copyright (C) 2025 Free Software Foundation, Inc.
3 : Contributed by David Malcolm <dmalcolm@redhat.com>.
4 :
5 : This file is part of GCC.
6 :
7 : GCC is free software; you can redistribute it and/or modify it under
8 : the terms of the GNU General Public License as published by the Free
9 : Software Foundation; either version 3, or (at your option) any later
10 : version.
11 :
12 : GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 : WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 : FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 : for more details.
16 :
17 : You should have received a copy of the GNU General Public License
18 : along with GCC; see the file COPYING3. If not see
19 : <http://www.gnu.org/licenses/>. */
20 :
21 : #ifndef GCC_PUB_SUB_H
22 : #define GCC_PUB_SUB_H
23 :
24 : namespace pub_sub {
25 :
26 : template <typename Subscriber>
27 256629 : class channel
28 : {
29 : public:
30 : using subscriber = Subscriber;
31 :
32 : // A node within the std::list
33 : using subscription = typename std::list<subscriber *>::iterator;
34 :
35 : /* Return this if this channel has subscribers, or nullptr if
36 : there are none. */
37 : const channel *
38 784626038 : get_if_active () const
39 : {
40 784626038 : if (m_subscribers.empty ())
41 : return nullptr;
42 : return this;
43 : }
44 :
45 : template <typename Message>
46 610 : void publish (const Message &m) const
47 : {
48 1518 : for (auto sub : m_subscribers)
49 908 : sub->on_message (m);
50 610 : }
51 :
52 : subscription
53 26 : add_subscriber (subscriber &s)
54 : {
55 26 : return m_subscribers.insert (m_subscribers.end (), &s);
56 : }
57 : void unsubscribe (subscription s)
58 : {
59 : m_subscribers.remove (s);
60 : }
61 :
62 : private:
63 : std::list<subscriber *> m_subscribers;
64 : };
65 :
66 : } // namespace pub_sub
67 :
68 : #endif /* GCC_PUB_SUB_H */
|