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
#![warn(clippy::or_fun_call)]
28
#![deny(clippy::print_stderr)]
29
#![deny(clippy::print_stdout)]
30
#![warn(clippy::rc_buffer)]
31
#![deny(clippy::ref_option_ref)]
32
#![warn(clippy::semicolon_if_nothing_returned)]
33
#![warn(clippy::trait_duplication_in_bounds)]
34
#![deny(clippy::unchecked_time_subtraction)]
35
#![deny(clippy::unnecessary_wraps)]
36
#![warn(clippy::unseparated_literal_suffix)]
37
#![deny(clippy::unwrap_used)]
38
#![deny(clippy::mod_module_files)]
39
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
40
#![allow(clippy::uninlined_format_args)]
41
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
42
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
43
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
44
#![allow(clippy::needless_lifetimes)] // See arti#1765
45
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
46
#![allow(clippy::collapsible_if)] // See arti#2342
47
#![deny(clippy::unused_async)]
48
#![deny(clippy::string_slice)] // See arti#2571
49
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
50
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
51

            
52
// TODO: add to the list maintained by maint/add_warning once it's available on all crates
53
#![warn(unnameable_types)]
54

            
55
mod arc_io_result;
56
mod copy_buf;
57
mod copy_buf_bidi;
58
pub mod eof;
59
mod fuse_buf_reader;
60
use std::{
61
    future::Future,
62
    pin::Pin,
63
    task::{Context, Poll},
64
};
65

            
66
pub use copy_buf::{CopyBuf, copy_buf};
67
pub use copy_buf_bidi::{CopyBufBidirectional, copy_buf_bidirectional};
68
pub use eof::EofStrategy;
69

            
70
use futures::{AsyncRead, AsyncWrite, io::BufReader};
71
use pin_project::pin_project;
72

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

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

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

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

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

            
164
impl<R, W> Future for Copy<R, W>
165
where
166
    R: AsyncRead,
167
    W: AsyncWrite,
168
{
169
    type Output = std::io::Result<u64>;
170

            
171
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
172
        self.project().0.poll(cx)
173
    }
174
}
175

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

            
185
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
186
        self.project().0.poll(cx)
187
    }
188
}
189

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

            
207
    use super::*;
208
    use std::io;
209

            
210
    /// A struct that implements AsyncRead and AsyncWrite, but always returns an error.
211
    #[derive(Debug, Clone)]
212
    pub(crate) struct ErrorRW(pub(crate) io::ErrorKind);
213

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

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

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

            
237
        fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
238
            Poll::Ready(Err(io::Error::from(self.0)))
239
        }
240
    }
241

            
242
    /// A struct that implements AsyncRead, but never returns any data.
243
    ///
244
    /// (This reader is always _pending_.)
245
    pub(crate) struct PausedRead;
246

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

            
257
    /// A read-write pair, stapled into a Read+Write stream.
258
    #[pin_project]
259
    pub(crate) struct RWPair<R, W>(#[pin] pub(crate) R, #[pin] pub(crate) W);
260

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

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

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

            
284
        fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
285
            self.project().1.poll_close(cx)
286
        }
287
    }
288
}