tiny_std/unix/
fd.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use core::marker::PhantomData;

use rusl::platform::{Fd, OpenFlags};
use rusl::unistd::fcntl_set_file_status;

pub type RawFd = Fd;

#[repr(transparent)]
#[derive(Debug)]
pub struct OwnedFd(pub(crate) RawFd);

impl OwnedFd {
    /// Create an `OwnedFd` from a `RawFd`
    /// # Safety
    /// `fd` is valid and not used elsewhere, see `File::from_raw_fd`
    #[must_use]
    pub const unsafe fn from_raw(raw: RawFd) -> Self {
        Self(raw)
    }

    /// Sets this owned FD as non-blocking
    /// # Errors
    /// This FD is invalid, through unsafe creation
    #[inline]
    pub fn set_nonblocking(&self) -> crate::error::Result<()> {
        set_fd_nonblocking(self.as_raw_fd())
    }
}

impl AsRawFd for OwnedFd {
    #[inline]
    fn as_raw_fd(&self) -> RawFd {
        self.0
    }
}

impl Drop for OwnedFd {
    fn drop(&mut self) {
        // Best attempt
        let _ = rusl::unistd::close(self.0);
    }
}

#[repr(transparent)]
#[derive(Debug, Copy, Clone)]
pub struct BorrowedFd<'fd> {
    pub(crate) fd: RawFd,
    _pd: PhantomData<&'fd OwnedFd>,
}

impl<'a> BorrowedFd<'a> {
    pub(crate) fn new(fd: RawFd) -> Self {
        Self {
            fd,
            _pd: PhantomData,
        }
    }
}

impl<'a> AsRawFd for BorrowedFd<'a> {
    #[inline]
    fn as_raw_fd(&self) -> RawFd {
        self.fd
    }
}

pub trait AsRawFd {
    fn as_raw_fd(&self) -> RawFd;
}

#[inline]
pub(crate) fn set_fd_nonblocking(raw_fd: RawFd) -> crate::error::Result<()> {
    let orig = rusl::unistd::fcntl_get_file_status(raw_fd)?;
    fcntl_set_file_status(raw_fd, orig | OpenFlags::O_NONBLOCK)?;
    Ok(())
}