]> git.proxmox.com Git - rustc.git/blob - src/libstd/sys/redox/fd.rs
New upstream version 1.37.0+dfsg1
[rustc.git] / src / libstd / sys / redox / fd.rs
1 #![unstable(reason = "not public", issue = "0", feature = "fd")]
2
3 use crate::io::{self, Read};
4 use crate::mem;
5 use crate::sys::{cvt, syscall};
6 use crate::sys_common::AsInner;
7
8 pub struct FileDesc {
9 fd: usize,
10 }
11
12 impl FileDesc {
13 pub fn new(fd: usize) -> FileDesc {
14 FileDesc { fd }
15 }
16
17 pub fn raw(&self) -> usize { self.fd }
18
19 /// Extracts the actual file descriptor without closing it.
20 pub fn into_raw(self) -> usize {
21 let fd = self.fd;
22 mem::forget(self);
23 fd
24 }
25
26 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
27 cvt(syscall::read(self.fd, buf))
28 }
29
30 pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
31 let mut me = self;
32 (&mut me).read_to_end(buf)
33 }
34
35 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
36 cvt(syscall::write(self.fd, buf))
37 }
38
39 pub fn duplicate(&self) -> io::Result<FileDesc> {
40 self.duplicate_path(&[])
41 }
42 pub fn duplicate_path(&self, path: &[u8]) -> io::Result<FileDesc> {
43 let new_fd = cvt(syscall::dup(self.fd, path))?;
44 Ok(FileDesc::new(new_fd))
45 }
46
47 pub fn nonblocking(&self) -> io::Result<bool> {
48 let flags = cvt(syscall::fcntl(self.fd, syscall::F_GETFL, 0))?;
49 Ok(flags & syscall::O_NONBLOCK == syscall::O_NONBLOCK)
50 }
51
52 pub fn set_cloexec(&self) -> io::Result<()> {
53 let mut flags = cvt(syscall::fcntl(self.fd, syscall::F_GETFD, 0))?;
54 flags |= syscall::O_CLOEXEC;
55 cvt(syscall::fcntl(self.fd, syscall::F_SETFD, flags)).and(Ok(()))
56 }
57
58 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
59 let mut flags = cvt(syscall::fcntl(self.fd, syscall::F_GETFL, 0))?;
60 if nonblocking {
61 flags |= syscall::O_NONBLOCK;
62 } else {
63 flags &= !syscall::O_NONBLOCK;
64 }
65 cvt(syscall::fcntl(self.fd, syscall::F_SETFL, flags)).and(Ok(()))
66 }
67 }
68
69 impl<'a> Read for &'a FileDesc {
70 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
71 (**self).read(buf)
72 }
73 }
74
75 impl AsInner<usize> for FileDesc {
76 fn as_inner(&self) -> &usize { &self.fd }
77 }
78
79 impl Drop for FileDesc {
80 fn drop(&mut self) {
81 // Note that errors are ignored when closing a file descriptor. The
82 // reason for this is that if an error occurs we don't actually know if
83 // the file descriptor was closed or not, and if we retried (for
84 // something like EINTR), we might close another valid file descriptor
85 // (opened after we closed ours.
86 let _ = syscall::close(self.fd);
87 }
88 }