cap_primitives/rustix/fs/
permissions_ext.rs

1use crate::fs::Permissions;
2use rustix::fs::RawMode;
3use std::fs;
4
5#[derive(Debug, Clone, Eq, PartialEq)]
6pub(crate) struct ImplPermissionsExt {
7    #[cfg(not(target_os = "wasi"))]
8    mode: RawMode,
9}
10
11#[cfg(not(target_os = "wasi"))]
12impl ImplPermissionsExt {
13    /// Constructs a new instance of `Self` from the given
14    /// [`std::fs::Permissions`].
15    #[inline]
16    pub(crate) fn from_std(std: fs::Permissions) -> Self {
17        use std::os::unix::fs::PermissionsExt;
18        Self {
19            mode: std.mode() as RawMode,
20        }
21    }
22
23    /// Constructs a new instance of `Permissions` from the given
24    /// `RawMode`.
25    #[inline]
26    pub(crate) const fn from_raw_mode(mode: RawMode) -> Permissions {
27        Permissions {
28            readonly: Self::readonly(mode),
29            ext: Self { mode },
30        }
31    }
32
33    /// Test whether the given `RawMode` lacks write permissions.
34    #[inline]
35    pub(crate) const fn readonly(mode: RawMode) -> bool {
36        mode & 0o222 == 0
37    }
38
39    /// Test whether the given `RawMode` lacks write permissions.
40    #[inline]
41    pub(crate) fn set_readonly(&mut self, readonly: bool) {
42        if readonly {
43            // remove write permission for all classes; equivalent to `chmod a-w <file>`
44            self.mode &= !0o222;
45        } else {
46            // add write permission for all classes; equivalent to `chmod a+w <file>`
47            self.mode |= 0o222;
48        }
49    }
50}
51
52#[cfg(not(target_os = "wasi"))]
53impl crate::fs::PermissionsExt for ImplPermissionsExt {
54    fn mode(&self) -> u32 {
55        self.mode as u32
56    }
57
58    fn set_mode(&mut self, mode: u32) {
59        self.mode = mode as RawMode & 0o7777;
60    }
61
62    fn from_mode(mode: u32) -> Self {
63        Self {
64            mode: mode as RawMode & 0o7777,
65        }
66    }
67}
68
69#[cfg(target_os = "wasi")]
70impl ImplPermissionsExt {
71    pub(crate) fn default() -> Permissions {
72        Permissions { readonly: false }
73    }
74}