Skip to main content

compose_yml/v2/
permissions.rs

1use super::common::*;
2
3/// Permissions on devices that are mapped into the Docker container.
4#[derive(Debug, Eq, PartialEq, Clone, Copy)]
5pub struct DevicePermissions {
6    /// Can the container read from this device?
7    pub read: bool,
8    /// Can the container write to this device?
9    pub write: bool,
10    /// Can the container call `mknod` for this device?
11    pub mknod: bool,
12}
13
14impl Default for DevicePermissions {
15    fn default() -> DevicePermissions {
16        DevicePermissions {
17            read: true,
18            write: true,
19            mknod: true,
20        }
21    }
22}
23
24impl fmt::Display for DevicePermissions {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        if self.read {
27            write!(f, "r")?
28        }
29        if self.write {
30            write!(f, "w")?
31        }
32        if self.mknod {
33            write!(f, "m")?
34        }
35        Ok(())
36    }
37}
38
39impl FromStr for DevicePermissions {
40    type Err = Error;
41
42    fn from_str(s: &str) -> Result<Self> {
43        lazy_static! {
44            static ref PERMS: Regex = Regex::new("^(r)?(w)?(m)?").unwrap();
45        }
46        let caps = PERMS
47            .captures(s)
48            .ok_or_else(|| Error::invalid_value("restart-mode", s))?;
49        Ok(DevicePermissions {
50            read: caps.get(1).is_some(),
51            write: caps.get(2).is_some(),
52            mknod: caps.get(3).is_some(),
53        })
54    }
55}
56
57#[test]
58fn device_permissions_has_a_string_representation() {
59    let pairs = vec![
60        (Default::default(), "rwm"),
61        (
62            DevicePermissions {
63                read: false,
64                ..Default::default()
65            },
66            "wm",
67        ),
68        (
69            DevicePermissions {
70                write: false,
71                ..Default::default()
72            },
73            "rm",
74        ),
75        (
76            DevicePermissions {
77                mknod: false,
78                ..Default::default()
79            },
80            "rw",
81        ),
82    ];
83    for (mode, s) in pairs {
84        assert_eq!(mode.to_string(), s);
85        assert_eq!(mode, DevicePermissions::from_str(s).unwrap());
86    }
87}