read_write_ext_tokio/
lib.rs

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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
//! [![crates.io version](https://img.shields.io/crates/v/read-write-ext-tokio.svg)](https://crates.io/crates/read-write-ext-tokio)
//! [![license: Apache 2.0](https://gitlab.com/leonhard-llc/fixed-buffer-rs/-/raw/main/license-apache-2.0.svg)](http://www.apache.org/licenses/LICENSE-2.0)
//! [![unsafe forbidden](https://gitlab.com/leonhard-llc/fixed-buffer-rs/-/raw/main/unsafe-forbidden-success.svg)](https://github.com/rust-secure-code/safety-dance/)
//! [![pipeline status](https://gitlab.com/leonhard-llc/fixed-buffer-rs/badges/main/pipeline.svg)](https://gitlab.com/leonhard-llc/fixed-buffer-rs/-/pipelines)
//!
//! `AsyncReadWriteExt` trait with `chain_after` and `take_rw` for `tokio::io::Read + Write` structs.
//!
//! # Features
//! - `forbid(unsafe_code)`
//! - Good test coverage (100%)
//! - Like [`tokio::io::AsyncReadExt::chain`](https://docs.rs/tokio/latest/tokio/io/trait.AsyncReadExt.html#method.chain)
//!   and [`tokio::io::AsyncReadExt::take`](https://docs.rs/tokio/latest/tokio/io/trait.AsyncReadExt.html#method.take)
//!   but also passes through writes.
//! - Useful with `Read + Write` objects like
//!   [`tokio::net::TcpStream`](https://docs.rs/tokio/latest/tokio/net/struct.TcpStream.html)
//!   and [`tokio_rustls::TlsStream`](https://docs.rs/tokio-rustls/latest/tokio_rustls/enum.TlsStream.html).
//!
//! # Changelog
//! - v0.1.0 - Initial release.  Moved code from `fixed-buffer-tokio`.
//!
//! # TO DO
//!
//! # Release Process
//! 1. Edit `Cargo.toml` and bump version number.
//! 1. Run `../release.sh`
#![forbid(unsafe_code)]

use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};

/// A wrapper for a pair of structs, R and RW.
///
/// Implements `tokio::io::AsyncRead`.  Reads from `R` until it is empty, then reads from `RW`.
///
/// Implements `tokio::io::AsyncWrite`.  Passes all writes through to `RW`.
///
/// This is like the struct returned by
/// [`tokio::io::AsyncReadExt::chain`](https://docs.rs/tokio/latest/tokio/io/trait.AsyncReadExt.html#method.chain)
/// that also passes through writes.
pub struct AsyncReadWriteChain<R: AsyncRead, RW: AsyncRead + AsyncWrite> {
    reader: Option<R>,
    read_writer: RW,
}
impl<R: AsyncRead, RW: AsyncRead + AsyncWrite> AsyncReadWriteChain<R, RW> {
    /// See [`AsyncReadWriteChain`](struct.AsyncReadWriteChain.html).
    pub fn new(reader: R, read_writer: RW) -> AsyncReadWriteChain<R, RW> {
        Self {
            reader: Some(reader),
            read_writer,
        }
    }
}
impl<R: AsyncRead + Unpin, RW: AsyncRead + AsyncWrite + Unpin> AsyncRead
    for AsyncReadWriteChain<R, RW>
{
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<Result<(), std::io::Error>> {
        if let Some(ref mut reader) = self.reader {
            let before_len = buf.filled().len();
            match Pin::new(&mut *reader).poll_read(cx, buf) {
                Poll::Pending => return Poll::Pending,
                Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
                Poll::Ready(Ok(())) => {
                    let num_read = buf.filled().len() - before_len;
                    if num_read > 0 {
                        return Poll::Ready(Ok(()));
                    }
                    // EOF
                    self.reader = None;
                    // Fall through.
                }
            }
        }
        Pin::new(&mut self.read_writer).poll_read(cx, buf)
    }
}
impl<R: AsyncRead + Unpin, RW: AsyncRead + AsyncWrite + Unpin> AsyncWrite
    for AsyncReadWriteChain<R, RW>
{
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<Result<usize, std::io::Error>> {
        Pin::new(&mut self.read_writer).poll_write(cx, buf)
    }

    fn poll_flush(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Result<(), std::io::Error>> {
        Pin::new(&mut self.read_writer).poll_flush(cx)
    }

    fn poll_shutdown(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Result<(), std::io::Error>> {
        Pin::new(&mut self.read_writer).poll_shutdown(cx)
    }
}

/// Wraps a `tokio::io::AsyncRead + tokio::io::AsyncWrite` struct.
/// Passes through reads and writes to the struct.
/// Limits the number of bytes that can be read.
///
/// This is like [`tokio::io::Take`](https://docs.rs/tokio/latest/tokio/io/struct.Take.html)
/// that also passes through writes.
pub struct AsyncReadWriteTake<RW: AsyncRead + AsyncWrite> {
    read_writer: RW,
    remaining_bytes: u64,
}
impl<RW: AsyncRead + AsyncWrite + Unpin> AsyncReadWriteTake<RW> {
    /// See [`AsyncReadWriteTake`](struct.AsyncReadWriteTake.html).
    pub fn new(read_writer: RW, len: u64) -> AsyncReadWriteTake<RW> {
        Self {
            read_writer,
            remaining_bytes: len,
        }
    }
}
impl<RW: AsyncRead + AsyncWrite + Unpin> AsyncRead for AsyncReadWriteTake<RW> {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<Result<(), std::io::Error>> {
        if self.remaining_bytes == 0 {
            return Poll::Ready(Ok(()));
        }
        let num_to_read =
            usize::try_from(self.remaining_bytes.min(buf.remaining() as u64)).unwrap_or(usize::MAX);
        let dest = &mut buf.initialize_unfilled()[0..num_to_read];
        let mut buf2 = ReadBuf::new(dest);
        match Pin::new(&mut self.read_writer).poll_read(cx, &mut buf2) {
            Poll::Ready(Ok(())) => {
                let num_read = buf2.filled().len();
                buf.advance(num_read);
                self.remaining_bytes -= num_read as u64;
                Poll::Ready(Ok(()))
            }
            Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
            Poll::Pending => Poll::Pending,
        }
    }
}
impl<RW: AsyncRead + AsyncWrite + Unpin> AsyncWrite for AsyncReadWriteTake<RW> {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<Result<usize, std::io::Error>> {
        Pin::new(&mut self.read_writer).poll_write(cx, buf)
    }

    fn poll_flush(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Result<(), std::io::Error>> {
        Pin::new(&mut self.read_writer).poll_flush(cx)
    }

    fn poll_shutdown(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Result<(), std::io::Error>> {
        Pin::new(&mut self.read_writer).poll_shutdown(cx)
    }
}
pub trait AsyncReadWriteExt: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin {
    /// Returns a struct that implements `tokio::io::AsyncRead` and `tokio::io::AsyncWrite`.
    ///
    /// It reads from `reader` until it is empty, then reads from `self`.
    ///
    /// It passes all writes through to `self`.
    ///
    /// This is like [`tokio::io::AsyncReadExt::chain`](https://docs.rs/tokio/latest/tokio/io/trait.AsyncReadExt.html#method.chain)
    /// that also passes through writes.
    fn chain_after<R: tokio::io::AsyncRead>(
        &mut self,
        reader: R,
    ) -> AsyncReadWriteChain<R, &mut Self> {
        AsyncReadWriteChain::new(reader, self)
    }

    /// Wraps a struct that implements `tokio::io::AsyncRead` and `tokio::io::AsyncWrite`.
    ///
    /// The returned struct passes through reads and writes to the struct.
    ///
    /// It limits the number of bytes that can be read.
    ///
    /// This is like [`tokio::io::AsyncReadExt::take`](https://docs.rs/tokio/latest/tokio/io/trait.AsyncReadExt.html#method.take)
    /// that also passes through writes.
    fn take_rw(&mut self, len: u64) -> AsyncReadWriteTake<&mut Self> {
        AsyncReadWriteTake::new(self, len)
    }
}
impl<RW: tokio::io::AsyncRead + tokio::io::AsyncWrite + ?Sized + Unpin> AsyncReadWriteExt for RW {}