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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#![unstable(reason = "not public", issue = "0", feature = "fd")]
use io::{self, Read};
use mem;
use sys::{cvt, syscall};
use sys_common::AsInner;
pub struct FileDesc {
fd: usize,
}
impl FileDesc {
pub fn new(fd: usize) -> FileDesc {
FileDesc { fd: fd }
}
pub fn raw(&self) -> usize { self.fd }
pub fn into_raw(self) -> usize {
let fd = self.fd;
mem::forget(self);
fd
}
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
cvt(syscall::read(self.fd, buf))
}
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> {
cvt(syscall::write(self.fd, buf))
}
pub fn duplicate(&self) -> io::Result<FileDesc> {
let new_fd = cvt(syscall::dup(self.fd, &[]))?;
Ok(FileDesc::new(new_fd))
}
pub fn nonblocking(&self) -> io::Result<bool> {
let flags = cvt(syscall::fcntl(self.fd, syscall::F_GETFL, 0))?;
Ok(flags & syscall::O_NONBLOCK == syscall::O_NONBLOCK)
}
pub fn set_cloexec(&self) -> io::Result<()> {
let mut flags = cvt(syscall::fcntl(self.fd, syscall::F_GETFD, 0))?;
flags |= syscall::O_CLOEXEC;
cvt(syscall::fcntl(self.fd, syscall::F_SETFD, flags)).and(Ok(()))
}
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
let mut flags = cvt(syscall::fcntl(self.fd, syscall::F_GETFL, 0))?;
if nonblocking {
flags |= syscall::O_NONBLOCK;
} else {
flags &= !syscall::O_NONBLOCK;
}
cvt(syscall::fcntl(self.fd, syscall::F_SETFL, flags)).and(Ok(()))
}
}
impl<'a> Read for &'a FileDesc {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
(**self).read(buf)
}
}
impl AsInner<usize> for FileDesc {
fn as_inner(&self) -> &usize { &self.fd }
}
impl Drop for FileDesc {
fn drop(&mut self) {
let _ = syscall::close(self.fd);
}
}