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_loff_t;
22#[allow(non_camel_case_types)]
23pub type kernel_loff_t = linux___kernel_loff_t;
24
25pub use bindings::linux___kernel_size_t;
26#[allow(non_camel_case_types)]
27pub type kernel_size_t = linux___kernel_size_t;
28
29pub use bindings::linux___kernel_fd_set;
30#[allow(non_camel_case_types)]
31pub type kernel_fd_set = linux___kernel_fd_set;
32
33pub use bindings::linux___kernel_uid32_t;
34#[allow(non_camel_case_types)]
35pub type kernel_uid32_t = linux___kernel_uid32_t;
36
37pub use bindings::linux___kernel_gid32_t;
38#[allow(non_camel_case_types)]
39pub type kernel_gid32_t = linux___kernel_gid32_t;
40
41/// Type-safe wrapper around [`kernel_pid_t`]. Value is strictly positive.
42/// Interface inspired by `rustix::process::Pid`.
43#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
44pub struct Pid(NonZeroI32);
45
46impl Pid {
47    pub fn from_raw(pid: kernel_pid_t) -> Option<Self> {
48        if pid < 0 {
49            None
50        } else {
51            Some(Self(NonZeroI32::new(pid).unwrap()))
52        }
53    }
54
55    /// Returns a stricly positive integer for `Some`, or 0 for `None`.
56    pub fn as_raw(this: Option<Self>) -> kernel_pid_t {
57        this.map(|x| kernel_pid_t::from(x.0)).unwrap_or(0)
58    }
59
60    pub fn as_raw_nonzero(self) -> NonZeroI32 {
61        self.0
62    }
63}
64
65#[cfg(feature = "rustix")]
66impl From<rustix::process::Pid> for Pid {
67    fn from(value: rustix::process::Pid) -> Self {
68        Pid(value.as_raw_nonzero())
69    }
70}
71
72#[cfg(feature = "rustix")]
73impl From<Pid> for rustix::process::Pid {
74    fn from(value: Pid) -> Self {
75        rustix::process::Pid::from_raw(value.as_raw_nonzero().into()).unwrap()
76    }
77}
78
79/// A raw file descriptor value.
80// Considered newtype'ing this and restricting to unsigned, but
81// for now sticking to the precedent of a simple alias as per
82// `std::os::fd::RawFd`, and `rustix::fd::RawFd`.
83pub type RawFd = i32;