1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
use crate::{DBus, DBusResult};
use async_trait::async_trait;
use dbus_message_parser::Message;
use futures::channel::mpsc::{channel, Receiver};
use futures::lock::Mutex;
use futures::StreamExt;
use std::sync::Arc;

/// A trait for the generic `Message` handler.
#[async_trait]
pub trait Handler: Sized + Send + Sync + 'static {
    /// Handle the `Message`.
    async fn handle(&mut self, dbus: &DBus, msg: Message) -> DBusResult<()>;
}

#[async_trait]
pub trait Binder: Sized + Send + Sync + 'static {
    async fn bind(self, dbus: DBus, object_path: &str) -> DBusResult<()> {
        let (sender, receiver) = channel(128);
        dbus.add_object_path(object_path.to_string(), sender)?;
        self.bind_by_receiver(dbus, receiver).await
    }

    async fn bind_by_receiver(self, dbus: DBus, receiver: Receiver<Message>) -> DBusResult<()>;
}

// TODO: Wait until specialization https://github.com/rust-lang/rust/issues/31844 is finished to
// define a default impl with Deletable
#[async_trait]
impl<T> Binder for T
where
    T: Handler,
{
    async fn bind_by_receiver(
        mut self,
        dbus: DBus,
        mut receiver: Receiver<Message>,
    ) -> DBusResult<()> {
        while let Some(msg) = receiver.next().await {
            self.handle(&dbus, msg).await?;
        }
        Ok(())
    }
}

// TODO: Wait until specialization https://github.com/rust-lang/rust/issues/31844 is finished to
// define a default impl with Deletable
#[async_trait]
impl<T> Binder for Arc<Mutex<T>>
where
    T: Handler,
{
    async fn bind_by_receiver(self, dbus: DBus, mut receiver: Receiver<Message>) -> DBusResult<()> {
        while let Some(msg) = receiver.next().await {
            let mut guard = self.lock().await;
            guard.handle(&dbus, msg).await?;
        }
        Ok(())
    }
}