rustix/
ugid.rs

1//! User and Group ID types.
2
3#![allow(unsafe_code)]
4
5use crate::backend::c;
6
7/// A group identifier as a raw integer.
8#[cfg(not(target_os = "wasi"))]
9pub type RawGid = c::gid_t;
10/// A user identifier as a raw integer.
11#[cfg(not(target_os = "wasi"))]
12pub type RawUid = c::uid_t;
13
14/// `uid_t`—A Unix user ID.
15#[repr(transparent)]
16#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
17pub struct Uid(RawUid);
18
19/// `gid_t`—A Unix group ID.
20#[repr(transparent)]
21#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
22pub struct Gid(RawGid);
23
24impl Uid {
25    /// A `Uid` corresponding to the root user (uid 0).
26    pub const ROOT: Self = Self(0);
27
28    /// Converts a `RawUid` into a `Uid`.
29    ///
30    /// # Safety
31    ///
32    /// `raw` must be the value of a valid Unix user ID.
33    #[inline]
34    pub const unsafe fn from_raw(raw: RawUid) -> Self {
35        Self(raw)
36    }
37
38    /// Converts a `Uid` into a `RawUid`.
39    #[inline]
40    pub const fn as_raw(self) -> RawUid {
41        self.0
42    }
43
44    /// Test whether this uid represents the root user (uid 0).
45    #[inline]
46    pub const fn is_root(self) -> bool {
47        self.0 == Self::ROOT.0
48    }
49}
50
51impl Gid {
52    /// A `Gid` corresponding to the root group (gid 0).
53    pub const ROOT: Self = Self(0);
54
55    /// Converts a `RawGid` into a `Gid`.
56    ///
57    /// # Safety
58    ///
59    /// `raw` must be the value of a valid Unix group ID.
60    #[inline]
61    pub const unsafe fn from_raw(raw: RawGid) -> Self {
62        Self(raw)
63    }
64
65    /// Converts a `Gid` into a `RawGid`.
66    #[inline]
67    pub const fn as_raw(self) -> RawGid {
68        self.0
69    }
70
71    /// Test whether this gid represents the root group (gid 0).
72    #[inline]
73    pub const fn is_root(self) -> bool {
74        self.0 == Self::ROOT.0
75    }
76}
77
78// Return the raw value of the IDs. In case of `None` it returns `!0` since it
79// has the same bit pattern as `-1` indicating no change to the owner/group ID.
80pub(crate) fn translate_fchown_args(owner: Option<Uid>, group: Option<Gid>) -> (RawUid, RawGid) {
81    let ow = match owner {
82        Some(o) => o.as_raw(),
83        None => !0,
84    };
85
86    let gr = match group {
87        Some(g) => g.as_raw(),
88        None => !0,
89    };
90
91    (ow, gr)
92}
93
94#[test]
95fn test_sizes() {
96    assert_eq_size!(RawUid, u32);
97    assert_eq_size!(RawGid, u32);
98}