Skip to main content

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