dbus_addr/transport/
vsock.rs

1use std::marker::PhantomData;
2
3use super::{percent::decode_percents_str, DBusAddr, Error, KeyValFmt, Result, TransportImpl};
4
5/// `vsock:` D-Bus transport.
6#[derive(Clone, Debug, PartialEq, Eq)]
7pub struct Vsock<'a> {
8    // no cid means ANY
9    cid: Option<u32>,
10    // no port means ANY
11    port: Option<u32>,
12    // use a phantom lifetime for eventually future fields and consistency
13    phantom: PhantomData<&'a ()>,
14}
15
16impl<'a> Vsock<'a> {
17    /// The VSOCK port.
18    pub fn port(&self) -> Option<u32> {
19        self.port
20    }
21
22    /// The VSOCK CID.
23    pub fn cid(&self) -> Option<u32> {
24        self.cid
25    }
26
27    /// Convert into owned version, with 'static lifetime.
28    pub fn into_owned(self) -> Vsock<'static> {
29        Vsock {
30            cid: self.cid,
31            port: self.port,
32            phantom: PhantomData,
33        }
34    }
35}
36
37impl<'a> TransportImpl<'a> for Vsock<'a> {
38    fn for_address(s: &'a DBusAddr<'a>) -> Result<Self> {
39        let mut port = None;
40        let mut cid = None;
41
42        for (k, v) in s.key_val_iter() {
43            match (k, v) {
44                ("port", Some(v)) => {
45                    port = Some(
46                        decode_percents_str(v)?
47                            .parse()
48                            .map_err(|_| Error::InvalidValue(k.into()))?,
49                    );
50                }
51                ("cid", Some(v)) => {
52                    cid = Some(
53                        decode_percents_str(v)?
54                            .parse()
55                            .map_err(|_| Error::InvalidValue(k.into()))?,
56                    )
57                }
58                _ => continue,
59            }
60        }
61
62        Ok(Vsock {
63            port,
64            cid,
65            phantom: PhantomData,
66        })
67    }
68
69    fn fmt_key_val<'s: 'b, 'b>(&'s self, kv: KeyValFmt<'b>) -> KeyValFmt<'b> {
70        kv.add("cid", self.cid()).add("port", self.port())
71    }
72}