asyncio/
posix.rs

1use prelude::IoControl;
2use ffi::{RawFd, AsRawFd, ioctl};
3use core::{IoContext, AsIoContext, AsyncFd};
4use async::Handler;
5use streams::Stream;
6use reactive_io::{AsAsyncFd, read, async_read, write, async_write, cancel,
7                  getnonblock, setnonblock};
8
9use std::io;
10
11/// Typedef for the typical usage of a stream-oriented descriptor.
12pub struct StreamDescriptor {
13    fd: AsyncFd,
14}
15
16impl StreamDescriptor {
17    pub unsafe fn from_raw_fd(ctx: &IoContext, fd: RawFd) -> StreamDescriptor {
18        StreamDescriptor {
19            fd: AsyncFd::new::<Self>(fd, ctx),
20        }
21    }
22
23    pub fn cancel(&self) {
24        cancel(self)
25    }
26
27    pub fn get_non_blocking(&self) -> io::Result<bool> {
28        getnonblock(self)
29    }
30
31    pub fn io_control<C>(&self, cmd: &mut C) -> io::Result<()>
32        where C: IoControl,
33    {
34        ioctl(self, cmd)
35    }
36
37    pub fn set_non_blocking(&self, on: bool) -> io::Result<()> {
38        setnonblock(self, on)
39    }
40}
41
42impl Stream<io::Error> for StreamDescriptor {
43    fn async_read_some<F>(&self, buf: &mut [u8], handler: F) -> F::Output
44        where F: Handler<usize, io::Error>,
45    {
46        async_read(self, buf, handler)
47    }
48
49    fn async_write_some<F>(&self, buf: &[u8], handler: F) -> F::Output
50        where F: Handler<usize, io::Error>
51    {
52        async_write(self, buf, handler)
53    }
54
55    fn read_some(&self, buf: &mut [u8]) -> io::Result<usize> {
56        read(self, buf)
57    }
58
59    fn write_some(&self, buf: &[u8]) -> io::Result<usize> {
60        write(self, buf)
61    }
62}
63
64impl AsRawFd for StreamDescriptor {
65    fn as_raw_fd(&self) -> RawFd {
66        self.fd.as_raw_fd()
67    }
68}
69
70unsafe impl Send for StreamDescriptor {
71}
72
73unsafe impl AsIoContext for StreamDescriptor {
74    fn as_ctx(&self) -> &IoContext {
75        self.fd.as_ctx()
76    }
77}
78
79impl AsAsyncFd for StreamDescriptor {
80    fn as_fd(&self) -> &AsyncFd {
81        &self.fd
82    }
83}