fd.rs 2.3 KB
Newer Older
1
#![unstable(reason = "not public", issue = "none", feature = "fd")]
2

D
David Tolnay 已提交
3
use crate::io::{self, ErrorKind, Read};
4 5
use crate::mem;
use crate::sys::cvt;
6
use crate::sys::hermit::abi;
7 8 9 10 11 12 13 14 15 16 17 18
use crate::sys_common::AsInner;

#[derive(Debug)]
pub struct FileDesc {
    fd: i32,
}

impl FileDesc {
    pub fn new(fd: i32) -> FileDesc {
        FileDesc { fd }
    }

D
David Tolnay 已提交
19 20 21
    pub fn raw(&self) -> i32 {
        self.fd
    }
22 23 24 25 26 27 28 29 30

    /// Extracts the actual file descriptor without closing it.
    pub fn into_raw(self) -> i32 {
        let fd = self.fd;
        mem::forget(self);
        fd
    }

    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
31
        let result = unsafe { abi::read(self.fd, buf.as_mut_ptr(), buf.len()) };
32 33 34 35 36 37 38 39 40
        cvt(result as i32)
    }

    pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
        let mut me = self;
        (&mut me).read_to_end(buf)
    }

    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
41
        let result = unsafe { abi::write(self.fd, buf.as_ptr(), buf.len()) };
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
        cvt(result as i32)
    }

    pub fn duplicate(&self) -> io::Result<FileDesc> {
        self.duplicate_path(&[])
    }
    pub fn duplicate_path(&self, _path: &[u8]) -> io::Result<FileDesc> {
        Err(io::Error::new(ErrorKind::Other, "duplicate isn't supported"))
    }

    pub fn nonblocking(&self) -> io::Result<bool> {
        Ok(false)
    }

    pub fn set_cloexec(&self) -> io::Result<()> {
        Err(io::Error::new(ErrorKind::Other, "cloexec isn't supported"))
    }

    pub fn set_nonblocking(&self, _nonblocking: bool) -> io::Result<()> {
        Err(io::Error::new(ErrorKind::Other, "nonblocking isn't supported"))
    }
}

impl<'a> Read for &'a FileDesc {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        (**self).read(buf)
    }
}

impl AsInner<i32> for FileDesc {
D
David Tolnay 已提交
72 73 74
    fn as_inner(&self) -> &i32 {
        &self.fd
    }
75 76 77 78 79 80 81 82 83
}

impl Drop for FileDesc {
    fn drop(&mut self) {
        // Note that errors are ignored when closing a file descriptor. The
        // reason for this is that if an error occurs we don't actually know if
        // the file descriptor was closed or not, and if we retried (for
        // something like EINTR), we might close another valid file descriptor
        // (opened after we closed ours.
84
        let _ = unsafe { abi::close(self.fd) };
85 86
    }
}