dbus_addr/
owned_address.rs

1use std::fmt;
2
3use super::{transport, transport::TransportImpl, DBusAddr, Error, Guid, KeyValFmt, Result};
4
5/// An owned bus address.
6///
7/// Example:
8/// ```
9/// use dbus_addr::OwnedDBusAddr;
10///
11/// let _: OwnedDBusAddr = "unix:path=/tmp/dbus.sock".try_into().unwrap();
12/// ```
13#[derive(Debug, PartialEq, Eq, Clone)]
14pub struct OwnedDBusAddr {
15    transport: transport::Transport<'static>,
16    guid: Option<Guid>,
17}
18
19impl OwnedDBusAddr {
20    /// The connection GUID if any.
21    pub fn guid(&self) -> Option<&Guid> {
22        self.guid.as_ref()
23    }
24
25    /// Transport connection details
26    pub fn transport(&self) -> &transport::Transport<'static> {
27        &self.transport
28    }
29
30    fn new(addr: &str) -> Result<Self> {
31        let addr = DBusAddr { addr: addr.into() };
32        let transport = addr.transport()?.into_owned();
33        let guid = addr.guid()?;
34        Ok(Self { transport, guid })
35    }
36}
37
38impl fmt::Display for OwnedDBusAddr {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        let kv = KeyValFmt::new().add("guid", self.guid.as_ref());
41        let t = &self.transport;
42        let kv = t.fmt_key_val(kv);
43        write!(f, "{t}:{kv}")?;
44        Ok(())
45    }
46}
47
48impl TryFrom<&str> for OwnedDBusAddr {
49    type Error = Error;
50
51    fn try_from(addr: &str) -> Result<Self> {
52        Self::new(addr)
53    }
54}
55
56impl TryFrom<String> for OwnedDBusAddr {
57    type Error = Error;
58
59    fn try_from(addr: String) -> Result<Self> {
60        Self::new(&addr)
61    }
62}
63
64/// A trait for objects which can be converted or resolved to one or more [`OwnedDBusAddr`] values.
65pub trait ToOwnedDBusAddrs<'a> {
66    type Iter: Iterator<Item = Result<OwnedDBusAddr>>;
67
68    /// Get an iterator over the D-Bus addresses.
69    fn to_owned_dbus_addrs(&'a self) -> Self::Iter;
70}
71
72impl<'a> ToOwnedDBusAddrs<'a> for str {
73    type Iter = std::iter::Once<Result<OwnedDBusAddr>>;
74
75    fn to_owned_dbus_addrs(&'a self) -> Self::Iter {
76        std::iter::once(self.try_into())
77    }
78}