1
#![cfg_attr(docsrs, feature(doc_cfg))]
2
#![doc = include_str!("../README.md")]
3
// @@ begin lint list maintained by maint/add_warning @@
4
#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5
#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6
#![warn(missing_docs)]
7
#![warn(noop_method_call)]
8
#![warn(unreachable_pub)]
9
#![warn(clippy::all)]
10
#![deny(clippy::await_holding_lock)]
11
#![deny(clippy::cargo_common_metadata)]
12
#![deny(clippy::cast_lossless)]
13
#![deny(clippy::checked_conversions)]
14
#![allow(clippy::cognitive_complexity)] // See arti#2556
15
#![deny(clippy::debug_assert_with_mut_call)]
16
#![deny(clippy::exhaustive_enums)]
17
#![deny(clippy::exhaustive_structs)]
18
#![deny(clippy::expl_impl_clone_on_copy)]
19
#![deny(clippy::fallible_impl_from)]
20
#![deny(clippy::implicit_clone)]
21
#![deny(clippy::large_stack_arrays)]
22
#![warn(clippy::manual_ok_or)]
23
#![deny(clippy::missing_docs_in_private_items)]
24
#![warn(clippy::needless_borrow)]
25
#![warn(clippy::needless_pass_by_value)]
26
#![warn(clippy::option_option)]
27
#![deny(clippy::print_stderr)]
28
#![deny(clippy::print_stdout)]
29
#![warn(clippy::rc_buffer)]
30
#![deny(clippy::ref_option_ref)]
31
#![warn(clippy::semicolon_if_nothing_returned)]
32
#![warn(clippy::trait_duplication_in_bounds)]
33
#![deny(clippy::unchecked_time_subtraction)]
34
#![deny(clippy::unnecessary_wraps)]
35
#![warn(clippy::unseparated_literal_suffix)]
36
#![deny(clippy::unwrap_used)]
37
#![deny(clippy::mod_module_files)]
38
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
39
#![allow(clippy::uninlined_format_args)]
40
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
41
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
42
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
43
#![allow(clippy::needless_lifetimes)] // See arti#1765
44
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45
#![allow(clippy::collapsible_if)] // See arti#2342
46
#![deny(clippy::unused_async)]
47
#![deny(clippy::string_slice)] // See arti#2571
48
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
49
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
50

            
51
mod arc_io_result;
52
mod copy_buf;
53
mod copy_buf_bidi;
54
pub mod eof;
55
mod fuse_buf_reader;
56
use std::{
57
    future::Future,
58
    pin::Pin,
59
    task::{Context, Poll},
60
};
61

            
62
pub use copy_buf::{CopyBuf, copy_buf};
63
pub use copy_buf_bidi::{CopyBufBidirectional, copy_buf_bidirectional};
64
pub use eof::EofStrategy;
65

            
66
use futures::{AsyncRead, AsyncWrite, io::BufReader};
67
use pin_project::pin_project;
68

            
69
/// Return a future to copy bytes from `reader` to `writer`.
70
///
71
/// See [`copy_buf()`] for full details.
72
///
73
/// Unlike `copy_buf`, this function does not require that `reader` implements AsyncBufRead:
74
/// it wraps `reader` internally in a new `BufReader` with default capacity.
75
///
76
/// ## Limitations
77
///
78
/// If an error occurs during transmission, buffered data that was read from `reader`
79
/// but not written to `writer` will be lost.
80
/// To avoid this, use [`copy_buf()`].
81
///
82
/// Similarly, if you drop this future while it is still pending,
83
/// any buffered data will be lost.
84
///
85
/// See the crate-level documentation for further
86
/// [discussion of this function's limitations](crate#Limitations).
87
pub fn copy<R, W>(reader: R, writer: W) -> Copy<R, W>
88
where
89
    R: AsyncRead,
90
    W: AsyncWrite,
91
{
92
    let reader = BufReader::new(reader);
93
    Copy(copy_buf(reader, writer))
94
}
95

            
96
/// Return a future to copies bytes from `stream_a` to `stream_b`,
97
/// and from `stream_b` to `stream_a`.
98
///
99
/// See [`copy_buf_bidirectional()`] for full details.
100
///
101
/// Unlike `copy_buf_bidirectional`, this function does not require that either stream implements AsyncBufRead:
102
/// it wraps them internally in a new `BufReader` with default capacity.
103
///
104
/// ## Limitations
105
///
106
/// If an error occurs during transmission, data that was read from one stream,
107
/// but not written to the other, will be lost.
108
/// To avoid this, use [`copy_buf_bidirectional()`].
109
///
110
/// Similarly, if you drop this future while it is still pending,
111
/// any buffered data will be lost.
112
///
113
/// See the crate-level documentation for further
114
/// [discussion of this function's limitations](crate#Limitations).
115
pub fn copy_bidirectional<A, B, AE, BE>(
116
    stream_a: A,
117
    stream_b: B,
118
    on_a_eof: AE,
119
    on_b_eof: BE,
120
) -> CopyBidirectional<A, B, AE, BE>
121
where
122
    A: AsyncRead + AsyncWrite,
123
    B: AsyncRead + AsyncWrite,
124
    AE: EofStrategy<B>,
125
    BE: EofStrategy<A>,
126
{
127
    let stream_a = BufReader::new(stream_a);
128
    let stream_b = BufReader::new(stream_b);
129
    CopyBidirectional(copy_buf_bidirectional(
130
        stream_a,
131
        stream_b,
132
        eof::BufReaderEofWrapper(on_a_eof),
133
        eof::BufReaderEofWrapper(on_b_eof),
134
    ))
135
}
136

            
137
/// A future returned by [`copy`].
138
#[derive(Debug)]
139
#[pin_project]
140
#[must_use = "futures do nothing unless you `.await` or poll them"]
141
pub struct Copy<R, W>(#[pin] CopyBuf<BufReader<R>, W>);
142

            
143
/// A future returned by [`copy_bidirectional`].
144
#[derive(Debug)]
145
#[pin_project]
146
#[must_use = "futures do nothing unless you `.await` or poll them"]
147
pub struct CopyBidirectional<A, B, AE, BE>(
148
    #[pin]
149
    CopyBufBidirectional<
150
        BufReader<A>,
151
        BufReader<B>,
152
        eof::BufReaderEofWrapper<AE>,
153
        eof::BufReaderEofWrapper<BE>,
154
    >,
155
);
156

            
157
// Note: There is intentionally no `into_inner` implementation for these types,
158
// since returning the original streams would discard any buffered data.
159

            
160
impl<R, W> Future for Copy<R, W>
161
where
162
    R: AsyncRead,
163
    W: AsyncWrite,
164
{
165
    type Output = std::io::Result<u64>;
166

            
167
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
168
        self.project().0.poll(cx)
169
    }
170
}
171

            
172
impl<A, B, AE, BE> Future for CopyBidirectional<A, B, AE, BE>
173
where
174
    A: AsyncRead + AsyncWrite,
175
    B: AsyncRead + AsyncWrite,
176
    AE: EofStrategy<B>,
177
    BE: EofStrategy<A>,
178
{
179
    type Output = std::io::Result<(u64, u64)>;
180

            
181
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
182
        self.project().0.poll(cx)
183
    }
184
}
185

            
186
#[cfg(test)]
187
mod test {
188
    // @@ begin test lint list maintained by maint/add_warning @@
189
    #![allow(clippy::bool_assert_comparison)]
190
    #![allow(clippy::clone_on_copy)]
191
    #![allow(clippy::dbg_macro)]
192
    #![allow(clippy::mixed_attributes_style)]
193
    #![allow(clippy::print_stderr)]
194
    #![allow(clippy::print_stdout)]
195
    #![allow(clippy::single_char_pattern)]
196
    #![allow(clippy::unwrap_used)]
197
    #![allow(clippy::unchecked_time_subtraction)]
198
    #![allow(clippy::useless_vec)]
199
    #![allow(clippy::needless_pass_by_value)]
200
    #![allow(clippy::string_slice)] // See arti#2571
201
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
202

            
203
    use super::*;
204
    use std::io;
205

            
206
    /// A struct that implements AsyncRead and AsyncWrite, but always returns an error.
207
    #[derive(Debug, Clone)]
208
    pub(crate) struct ErrorRW(pub(crate) io::ErrorKind);
209

            
210
    impl AsyncRead for ErrorRW {
211
        fn poll_read(
212
            self: Pin<&mut Self>,
213
            _cx: &mut Context<'_>,
214
            _buf: &mut [u8],
215
        ) -> Poll<io::Result<usize>> {
216
            Poll::Ready(Err(io::Error::from(self.0)))
217
        }
218
    }
219

            
220
    impl AsyncWrite for ErrorRW {
221
        fn poll_write(
222
            self: Pin<&mut Self>,
223
            _cx: &mut Context<'_>,
224
            _buf: &[u8],
225
        ) -> Poll<io::Result<usize>> {
226
            Poll::Ready(Err(io::Error::from(self.0)))
227
        }
228

            
229
        fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
230
            Poll::Ready(Err(io::Error::from(self.0)))
231
        }
232

            
233
        fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
234
            Poll::Ready(Err(io::Error::from(self.0)))
235
        }
236
    }
237

            
238
    /// A struct that implements AsyncRead, but never returns any data.
239
    ///
240
    /// (This reader is always _pending_.)
241
    pub(crate) struct PausedRead;
242

            
243
    impl AsyncRead for PausedRead {
244
        fn poll_read(
245
            self: Pin<&mut Self>,
246
            _cx: &mut Context<'_>,
247
            _buf: &mut [u8],
248
        ) -> Poll<io::Result<usize>> {
249
            Poll::Pending
250
        }
251
    }
252

            
253
    /// A read-write pair, stapled into a Read+Write stream.
254
    #[pin_project]
255
    pub(crate) struct RWPair<R, W>(#[pin] pub(crate) R, #[pin] pub(crate) W);
256

            
257
    impl<R: AsyncRead, W> AsyncRead for RWPair<R, W> {
258
        fn poll_read(
259
            self: Pin<&mut Self>,
260
            cx: &mut Context<'_>,
261
            buf: &mut [u8],
262
        ) -> Poll<io::Result<usize>> {
263
            self.project().0.poll_read(cx, buf)
264
        }
265
    }
266

            
267
    impl<R, W: AsyncWrite> AsyncWrite for RWPair<R, W> {
268
        fn poll_write(
269
            self: Pin<&mut Self>,
270
            cx: &mut Context<'_>,
271
            buf: &[u8],
272
        ) -> Poll<io::Result<usize>> {
273
            self.project().1.poll_write(cx, buf)
274
        }
275

            
276
        fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
277
            self.project().1.poll_flush(cx)
278
        }
279

            
280
        fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
281
            self.project().1.poll_close(cx)
282
        }
283
    }
284
}