Skip to content

Commit 721bedc

Browse files
authored
Make Uid::from_raw a safe function. (#1294)
And same for `Gid::from_raw`. These types don't lead anything to invoke undefined behavior, so their constructors don't need to be unsafe.
1 parent 237b8ac commit 721bedc

2 files changed

Lines changed: 23 additions & 15 deletions

File tree

src/pid.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,9 @@ impl Pid {
3636
/// [pidfd]: https://man7.org/linux/man-pages/man2/pidfd_open.2.html
3737
#[inline]
3838
pub const fn from_raw(raw: RawPid) -> Option<Self> {
39-
if raw > 0 {
40-
// SAFETY: We just checked that `raw > 0`.
41-
unsafe { Some(Self::from_raw_unchecked(raw)) }
42-
} else {
43-
None
39+
match NonZeroI32::new(raw) {
40+
Some(non_zero) => Some(Self(non_zero)),
41+
None => None,
4442
}
4543
}
4644

src/ugid.rs

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,11 @@
11
//! User and Group ID types.
22
3-
#![allow(unsafe_code)]
4-
53
use crate::backend::c;
64
use crate::ffi;
75

86
/// A group identifier as a raw integer.
9-
#[cfg(not(target_os = "wasi"))]
107
pub type RawGid = ffi::c_uint;
118
/// A user identifier as a raw integer.
12-
#[cfg(not(target_os = "wasi"))]
139
pub type RawUid = ffi::c_uint;
1410

1511
/// `uid_t`—A Unix user ID.
@@ -28,11 +24,18 @@ impl Uid {
2824

2925
/// Converts a `RawUid` into a `Uid`.
3026
///
31-
/// # Safety
27+
/// `raw` must be the value of a valid Unix user ID, and not `-1`.
28+
#[inline]
29+
pub fn from_raw(raw: RawUid) -> Self {
30+
debug_assert_ne!(raw, -1 as _);
31+
Self(raw)
32+
}
33+
34+
/// Converts a `RawUid` into a `Uid`.
3235
///
33-
/// `raw` must be the value of a valid Unix user ID.
36+
/// `raw` must be the value of a valid Unix user ID, and not `-1`.
3437
#[inline]
35-
pub const unsafe fn from_raw(raw: RawUid) -> Self {
38+
pub const fn from_raw_unchecked(raw: RawUid) -> Self {
3639
Self(raw)
3740
}
3841

@@ -55,11 +58,18 @@ impl Gid {
5558

5659
/// Converts a `RawGid` into a `Gid`.
5760
///
58-
/// # Safety
61+
/// `raw` must be the value of a valid Unix group ID, and not `-1`.
62+
#[inline]
63+
pub fn from_raw(raw: RawGid) -> Self {
64+
debug_assert_ne!(raw, -1 as _);
65+
Self(raw)
66+
}
67+
68+
/// Converts a `RawGid` into a `Gid`.
5969
///
60-
/// `raw` must be the value of a valid Unix group ID.
70+
/// `raw` must be the value of a valid Unix group ID, and not `-1`.
6171
#[inline]
62-
pub const unsafe fn from_raw(raw: RawGid) -> Self {
72+
pub const fn from_raw_unchecked(raw: RawGid) -> Self {
6373
Self(raw)
6474
}
6575

0 commit comments

Comments
 (0)