atm_io_utils/
duplex.rs

1use futures_core::Poll;
2use futures_core::task::Context;
3use futures_io::{AsyncRead, AsyncWrite, Error};
4
5/// Implements both AsyncRead and AsyncWrite by delegating to an AsyncRead
6/// and an AsyncWrite, taking ownership of both.
7#[derive(Debug, Copy, Clone, PartialEq, Eq)]
8pub struct Duplex<R, W> {
9    r: R,
10    w: W,
11}
12
13impl<R, W> Duplex<R, W> {
14    /// Takes ownership of a reader and a writer and creates a new `Duplex`.
15    pub fn new(r: R, w: W) -> Duplex<R, W> {
16        Duplex { r, w }
17    }
18
19    /// Gets a reference to the underlying reader.
20    pub fn get_reader_ref(&self) -> &R {
21        &self.r
22    }
23
24    /// Gets a mutable reference to the underlying reader.
25    pub fn get_reader_mut(&mut self) -> &mut R {
26        &mut self.r
27    }
28
29    /// Gets a reference to the underlying writer.
30    pub fn get_writer_ref(&self) -> &W {
31        &self.w
32    }
33
34    /// Gets a mutable reference to the underlying writer.
35    pub fn get_writer_mut(&mut self) -> &mut W {
36        &mut self.w
37    }
38
39    /// Unwraps this `Duplex`, returning the underlying reader and writer.
40    pub fn into_inner(self) -> (R, W) {
41        (self.r, self.w)
42    }
43}
44
45impl<R: AsyncRead, W> AsyncRead for Duplex<R, W> {
46    fn poll_read(&mut self, cx: &mut Context, buf: &mut [u8]) -> Poll<usize, Error> {
47        self.r.poll_read(cx, buf)
48    }
49}
50
51impl<R, W: AsyncWrite> AsyncWrite for Duplex<R, W> {
52    fn poll_write(&mut self, cx: &mut Context, buf: &[u8]) -> Poll<usize, Error> {
53        self.w.poll_write(cx, buf)
54    }
55
56    fn poll_flush(&mut self, cx: &mut Context) -> Poll<(), Error> {
57        self.w.poll_flush(cx)
58    }
59
60    fn poll_close(&mut self, cx: &mut Context) -> Poll<(), Error> {
61        self.w.poll_close(cx)
62    }
63}