tokio_io/
allow_std.rs

1use futures::{Async, Poll};
2use std::{fmt, io};
3use {AsyncRead, AsyncWrite};
4
5/// A simple wrapper type which allows types that only implement
6/// `std::io::Read` or `std::io::Write` to be used in contexts which expect
7/// an `AsyncRead` or `AsyncWrite`.
8///
9/// If these types issue an error with the kind `io::ErrorKind::WouldBlock`,
10/// it is expected that they will notify the current task on readiness.
11/// Synchronous `std` types should not issue errors of this kind and
12/// are safe to use in this context. However, using these types with
13/// `AllowStdIo` will cause the event loop to block, so they should be used
14/// with care.
15#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
16pub struct AllowStdIo<T>(T);
17
18impl<T> AllowStdIo<T> {
19    /// Creates a new `AllowStdIo` from an existing IO object.
20    pub fn new(io: T) -> Self {
21        AllowStdIo(io)
22    }
23
24    /// Returns a reference to the contained IO object.
25    pub fn get_ref(&self) -> &T {
26        &self.0
27    }
28
29    /// Returns a mutable reference to the contained IO object.
30    pub fn get_mut(&mut self) -> &mut T {
31        &mut self.0
32    }
33
34    /// Consumes self and returns the contained IO object.
35    pub fn into_inner(self) -> T {
36        self.0
37    }
38}
39
40impl<T> io::Write for AllowStdIo<T>
41where
42    T: io::Write,
43{
44    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
45        self.0.write(buf)
46    }
47    fn flush(&mut self) -> io::Result<()> {
48        self.0.flush()
49    }
50    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
51        self.0.write_all(buf)
52    }
53    fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> {
54        self.0.write_fmt(fmt)
55    }
56}
57
58impl<T> AsyncWrite for AllowStdIo<T>
59where
60    T: io::Write,
61{
62    fn shutdown(&mut self) -> Poll<(), io::Error> {
63        Ok(Async::Ready(()))
64    }
65}
66
67impl<T> io::Read for AllowStdIo<T>
68where
69    T: io::Read,
70{
71    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
72        self.0.read(buf)
73    }
74    // TODO: implement the `initializer` fn when it stabilizes.
75    // See rust-lang/rust #42788
76    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
77        self.0.read_to_end(buf)
78    }
79    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
80        self.0.read_to_string(buf)
81    }
82    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
83        self.0.read_exact(buf)
84    }
85}
86
87impl<T> AsyncRead for AllowStdIo<T>
88where
89    T: io::Read,
90{
91    // TODO: override prepare_uninitialized_buffer once `Read::initializer` is stable.
92    // See rust-lang/rust #42788
93}