Skip to main content

libc_rs/
fd.rs

1//! File descriptor types (`RawFd`, `BorrowedFd`, `OwnedFd`) and `*at` flags.
2
3use core::marker::PhantomData;
4use core::mem::ManuallyDrop;
5
6/// Raw file descriptor integer.
7pub type RawFd = i32;
8
9/// Special `dirfd` value indicating the current working directory.
10pub const AT_FDCWD: RawFd = -100;
11/// Do not follow symbolic links.
12pub const AT_SYMLINK_NOFOLLOW: i32 = 0x100;
13/// Remove directory instead of unlinking file.
14pub const AT_REMOVEDIR: i32 = 0x200;
15/// Operate on the `dirfd` itself when path is empty.
16pub const AT_EMPTY_PATH: i32 = 0x1000;
17
18/// Borrowed file descriptor tied to lifetime `'fd`.
19#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
20#[repr(transparent)]
21pub struct BorrowedFd<'fd> {
22    fd: RawFd,
23    _lt: PhantomData<&'fd ()>,
24}
25
26impl<'fd> BorrowedFd<'fd> {
27    /// Wraps a raw file descriptor in a [`BorrowedFd`] without taking ownership.
28    ///
29    /// # Safety
30    ///
31    /// `fd` must remain an open, valid file descriptor for the duration of `'fd`.
32    #[must_use]
33    pub const unsafe fn borrow_raw(fd: RawFd) -> Self {
34        Self {
35            fd,
36            _lt: PhantomData,
37        }
38    }
39
40    /// Returns the underlying [`RawFd`].
41    #[must_use]
42    pub const fn as_raw_fd(self) -> RawFd {
43        self.fd
44    }
45}
46
47/// Owned file descriptor that closes the underlying descriptor on drop.
48#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
49#[repr(transparent)]
50pub struct OwnedFd {
51    fd: RawFd,
52}
53
54impl OwnedFd {
55    /// Takes ownership of a raw file descriptor.
56    ///
57    /// # Safety
58    ///
59    /// `fd` must be an open, valid file descriptor uniquely owned by the caller.
60    #[must_use]
61    pub const unsafe fn from_raw_fd(fd: RawFd) -> Self {
62        Self { fd }
63    }
64
65    /// Returns the underlying [`RawFd`] without releasing ownership.
66    #[must_use]
67    pub const fn as_raw_fd(&self) -> RawFd {
68        self.fd
69    }
70
71    /// Consumes this [`OwnedFd`], returning the underlying [`RawFd`] without closing it.
72    #[must_use]
73    pub const fn into_raw_fd(self) -> RawFd {
74        let fd = self.fd;
75        let _ = ManuallyDrop::new(self);
76        fd
77    }
78
79    /// Borrows this descriptor as a [`BorrowedFd`].
80    #[must_use]
81    pub const fn as_fd(&self) -> BorrowedFd<'_> {
82        BorrowedFd {
83            fd: self.fd,
84            _lt: PhantomData,
85        }
86    }
87}
88
89impl Drop for OwnedFd {
90    fn drop(&mut self) {
91        let _ = crate::io::close(self.fd);
92    }
93}