Skip to content

Commit

Permalink
Make Uid::from_raw a safe function. (#1294)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
sunfishcode authored Jan 31, 2025
1 parent 237b8ac commit 721bedc
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 15 deletions.
8 changes: 3 additions & 5 deletions src/pid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,9 @@ impl Pid {
/// [pidfd]: https://man7.org/linux/man-pages/man2/pidfd_open.2.html
#[inline]
pub const fn from_raw(raw: RawPid) -> Option<Self> {
if raw > 0 {
// SAFETY: We just checked that `raw > 0`.
unsafe { Some(Self::from_raw_unchecked(raw)) }
} else {
None
match NonZeroI32::new(raw) {
Some(non_zero) => Some(Self(non_zero)),
None => None,
}
}

Expand Down
30 changes: 20 additions & 10 deletions src/ugid.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
//! User and Group ID types.
#![allow(unsafe_code)]

use crate::backend::c;
use crate::ffi;

/// A group identifier as a raw integer.
#[cfg(not(target_os = "wasi"))]
pub type RawGid = ffi::c_uint;
/// A user identifier as a raw integer.
#[cfg(not(target_os = "wasi"))]
pub type RawUid = ffi::c_uint;

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

/// Converts a `RawUid` into a `Uid`.
///
/// # Safety
/// `raw` must be the value of a valid Unix user ID, and not `-1`.
#[inline]
pub fn from_raw(raw: RawUid) -> Self {
debug_assert_ne!(raw, -1 as _);
Self(raw)
}

/// Converts a `RawUid` into a `Uid`.
///
/// `raw` must be the value of a valid Unix user ID.
/// `raw` must be the value of a valid Unix user ID, and not `-1`.
#[inline]
pub const unsafe fn from_raw(raw: RawUid) -> Self {
pub const fn from_raw_unchecked(raw: RawUid) -> Self {
Self(raw)
}

Expand All @@ -55,11 +58,18 @@ impl Gid {

/// Converts a `RawGid` into a `Gid`.
///
/// # Safety
/// `raw` must be the value of a valid Unix group ID, and not `-1`.
#[inline]
pub fn from_raw(raw: RawGid) -> Self {
debug_assert_ne!(raw, -1 as _);
Self(raw)
}

/// Converts a `RawGid` into a `Gid`.
///
/// `raw` must be the value of a valid Unix group ID.
/// `raw` must be the value of a valid Unix group ID, and not `-1`.
#[inline]
pub const unsafe fn from_raw(raw: RawGid) -> Self {
pub const fn from_raw_unchecked(raw: RawGid) -> Self {
Self(raw)
}

Expand Down

0 comments on commit 721bedc

Please sign in to comment.