xref: /openbmc/boost-dbus/include/dbus/filter.hpp (revision b573e22e)
1 // Copyright (c) Benjamin Kietzman (github.com/bkietz)
2 //
3 // Distributed under the Boost Software License, Version 1.0. (See accompanying
4 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
5 
6 #ifndef DBUS_FILTER_HPP
7 #define DBUS_FILTER_HPP
8 
9 #include <dbus/connection.hpp>
10 #include <dbus/detail/queue.hpp>
11 #include <dbus/message.hpp>
12 #include <functional>
13 #include <boost/asio.hpp>
14 
15 namespace dbus {
16 
17 /// Represents a filter of incoming messages.
18 /**
19  * Filters examine incoming messages, demuxing them to multiple queues.
20  */
21 class filter {
22   connection_ptr connection_;
23   std::function<bool(message&)> predicate_;
24   detail::queue<message> queue_;
25 
26  public:
offer(message & m)27   bool offer(message& m) {
28     bool filtered = predicate_(m);
29     if (filtered) queue_.push(m);
30     return filtered;
31   }
32 
33   template <typename MessagePredicate>
filter(connection_ptr c,BOOST_ASIO_MOVE_ARG (MessagePredicate)p)34   filter(connection_ptr c, BOOST_ASIO_MOVE_ARG(MessagePredicate) p)
35       : connection_(c),
36         predicate_(BOOST_ASIO_MOVE_CAST(MessagePredicate)(p)),
37         queue_(connection_->get_io_service()) {
38     connection_->new_filter(*this);
39   }
40 
~filter()41   ~filter() { connection_->delete_filter(*this); }
42 
43   template <typename MessageHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(MessageHandler,void (boost::system::error_code,message))44   inline BOOST_ASIO_INITFN_RESULT_TYPE(MessageHandler,
45                                        void(boost::system::error_code, message))
46       async_dispatch(BOOST_ASIO_MOVE_ARG(MessageHandler) handler) {
47     // begin asynchronous operation
48     connection_->get_implementation().start(connection_->get_io_service());
49 
50     return queue_.async_pop(BOOST_ASIO_MOVE_CAST(MessageHandler)(handler));
51   }
52 
53 };
54 }  // namespace dbus
55 
56 #include <dbus/impl/filter.ipp>
57 #endif  // DBUS_FILTER_HPP
58