linux_api/
posix_types.rs

1use core::num::NonZeroI32;
2
3use crate::bindings;
4
5pub use bindings::linux___kernel_pid_t;
6#[allow(non_camel_case_types)]
7pub type kernel_pid_t = linux___kernel_pid_t;
8
9pub use bindings::linux___kernel_mode_t;
10#[allow(non_camel_case_types)]
11pub type kernel_mode_t = bindings::linux___kernel_mode_t;
12
13pub use bindings::linux___kernel_ulong_t;
14#[allow(non_camel_case_types)]
15pub type kernel_ulong_t = bindings::linux___kernel_ulong_t;
16
17pub use bindings::linux___kernel_off_t;
18#[allow(non_camel_case_types)]
19pub type kernel_off_t = linux___kernel_off_t;
20
21pub use bindings::linux___kernel_size_t;
22#[allow(non_camel_case_types)]
23pub type kernel_size_t = linux___kernel_size_t;
24
25pub use bindings::linux___kernel_fd_set;
26#[allow(non_camel_case_types)]
27pub type kernel_fd_set = linux___kernel_fd_set;
28
29/// Type-safe wrapper around [`kernel_pid_t`]. Value is strictly positive.
30/// Interface inspired by `rustix::process::Pid`.
31#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
32pub struct Pid(NonZeroI32);
33
34impl Pid {
35    pub fn from_raw(pid: kernel_pid_t) -> Option<Self> {
36        if pid < 0 {
37            None
38        } else {
39            Some(Self(NonZeroI32::new(pid).unwrap()))
40        }
41    }
42
43    /// Returns a stricly positive integer for `Some`, or 0 for `None`.
44    pub fn as_raw(this: Option<Self>) -> kernel_pid_t {
45        this.map(|x| kernel_pid_t::from(x.0)).unwrap_or(0)
46    }
47
48    pub fn as_raw_nonzero(self) -> NonZeroI32 {
49        self.0
50    }
51}
52
53#[cfg(feature = "rustix")]
54impl From<rustix::process::Pid> for Pid {
55    fn from(value: rustix::process::Pid) -> Self {
56        Pid(value.as_raw_nonzero())
57    }
58}
59
60#[cfg(feature = "rustix")]
61impl From<Pid> for rustix::process::Pid {
62    fn from(value: Pid) -> Self {
63        rustix::process::Pid::from_raw(value.as_raw_nonzero().into()).unwrap()
64    }
65}
66
67/// A raw file descriptor value.
68// Considered newtype'ing this and restricting to unsigned, but
69// for now sticking to the precedent of a simple alias as per
70// `std::os::fd::RawFd`, and `rustix::fd::RawFd`.
71pub type RawFd = i32;