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