dbus_server_address_parser/decode/
address.rs

1use crate::{Address, Autolaunch, DecodeError, Launchd, NonceTcp, Systemd, Tcp, Unix, Unixexec};
2use std::convert::TryFrom;
3
4impl Address {
5    /// Decode [server addresses] separated by `;`.
6    ///
7    /// [server address]: https://dbus.freedesktop.org/doc/dbus-specification.html#addresses
8    pub fn decode(addresses: &str) -> Result<Vec<Address>, DecodeError> {
9        let mut result = Vec::new();
10        // Split by the ;, because it can have multiple addresses separated by a ;.
11        for address in addresses.split(';') {
12            let address = Address::try_from(address)?;
13            result.push(address);
14        }
15        Ok(result)
16    }
17}
18
19impl TryFrom<&str> for Address {
20    type Error = DecodeError;
21
22    fn try_from(address: &str) -> Result<Self, Self::Error> {
23        if let Some(unix) = address.strip_prefix("unix:") {
24            let unix = Unix::try_from(unix)?;
25            Ok(Address::Unix(unix))
26        } else if let Some(tcp) = address.strip_prefix("tcp:") {
27            let tcp = Tcp::try_from(tcp)?;
28            Ok(Address::Tcp(tcp))
29        } else if let Some(launchd) = address.strip_prefix("launchd:") {
30            let launchd = Launchd::try_from(launchd)?;
31            Ok(Address::Launchd(launchd))
32        } else if let Some(nonce_tcp) = address.strip_prefix("nonce-tcp:") {
33            let nonce_tcp = NonceTcp::try_from(nonce_tcp)?;
34            Ok(Address::NonceTcp(nonce_tcp))
35        } else if let Some(unixexec) = address.strip_prefix("unixexec:") {
36            let unixexec = Unixexec::try_from(unixexec)?;
37            Ok(Address::Unixexec(unixexec))
38        } else if let Some(systemd) = address.strip_prefix("systemd:") {
39            let systemd = Systemd::try_from(systemd)?;
40            Ok(Address::Systemd(systemd))
41        } else if let Some(autolaunch) = address.strip_prefix("autolaunch:") {
42            let autolaunch = Autolaunch::try_from(autolaunch)?;
43            Ok(Address::Autolaunch(autolaunch))
44        } else {
45            Err(DecodeError::UnknownType)
46        }
47    }
48}