1extern crate libc;
2
3pub fn cvt(t: ::libc::ssize_t) -> ::std::io::Result<::libc::ssize_t> {
5 if t == -1 {
6 Err(::std::io::Error::last_os_error())
7 } else {
8 Ok(t)
9 }
10}
11
12#[derive(Clone, Copy)]
13pub struct FdStream {
14 fd : ::libc::c_int,
15}
16
17impl FdStream {
18 pub fn new(fd : ::libc::c_int) -> FdStream {
19 FdStream { fd : fd }
20 }
21}
22
23impl ::std::io::Read for FdStream {
24 fn read(&mut self, buf : &mut [u8]) -> ::std::io::Result<usize> {
25 let ret = try!(cvt(unsafe {
26 ::libc::read(self.fd,
27 buf.as_mut_ptr() as *mut ::libc::c_void,
28 buf.len() as ::libc::size_t)
29 }));
30 Ok(ret as usize)
31 }
32}
33
34impl ::std::io::Write for FdStream {
35 fn write(&mut self, buf : &[u8]) -> ::std::io::Result<usize> {
36 let ret = try!(cvt(unsafe {
37 ::libc::write(self.fd,
38 buf.as_ptr() as *const ::libc::c_void,
39 buf.len() as ::libc::size_t)
40 }));
41 Ok(ret as usize)
42 }
43 fn flush(&mut self) -> ::std::io::Result<()> { Ok(()) }
44}