Skip to content

Commit c38da38

Browse files
committed
Use poll_fn in copy_bidirectional
1 parent 018d045 commit c38da38

File tree

1 file changed

+14
-43
lines changed

1 file changed

+14
-43
lines changed

tokio/src/io/util/copy_bidirectional.rs

Lines changed: 14 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
use super::copy::CopyBuffer;
22

3+
use crate::future::poll_fn;
34
use crate::io::{AsyncRead, AsyncWrite};
45

5-
use std::future::Future;
66
use std::io;
77
use std::pin::Pin;
88
use std::task::{Context, Poll};
@@ -13,13 +13,6 @@ enum TransferState {
1313
Done(u64),
1414
}
1515

16-
struct CopyBidirectional<'a, A: ?Sized, B: ?Sized> {
17-
a: &'a mut A,
18-
b: &'a mut B,
19-
a_to_b: TransferState,
20-
b_to_a: TransferState,
21-
}
22-
2316
fn transfer_one_direction<A, B>(
2417
cx: &mut Context<'_>,
2518
state: &mut TransferState,
@@ -48,35 +41,6 @@ where
4841
}
4942
}
5043
}
51-
52-
impl<'a, A, B> Future for CopyBidirectional<'a, A, B>
53-
where
54-
A: AsyncRead + AsyncWrite + Unpin + ?Sized,
55-
B: AsyncRead + AsyncWrite + Unpin + ?Sized,
56-
{
57-
type Output = io::Result<(u64, u64)>;
58-
59-
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
60-
// Unpack self into mut refs to each field to avoid borrow check issues.
61-
let CopyBidirectional {
62-
a,
63-
b,
64-
a_to_b,
65-
b_to_a,
66-
} = &mut *self;
67-
68-
let a_to_b = transfer_one_direction(cx, a_to_b, &mut *a, &mut *b)?;
69-
let b_to_a = transfer_one_direction(cx, b_to_a, &mut *b, &mut *a)?;
70-
71-
// It is not a problem if ready! returns early because transfer_one_direction for the
72-
// other direction will keep returning TransferState::Done(count) in future calls to poll
73-
let a_to_b = ready!(a_to_b);
74-
let b_to_a = ready!(b_to_a);
75-
76-
Poll::Ready(Ok((a_to_b, b_to_a)))
77-
}
78-
}
79-
8044
/// Copies data in both directions between `a` and `b`.
8145
///
8246
/// This function returns a future that will read from both streams,
@@ -110,11 +74,18 @@ where
11074
A: AsyncRead + AsyncWrite + Unpin + ?Sized,
11175
B: AsyncRead + AsyncWrite + Unpin + ?Sized,
11276
{
113-
CopyBidirectional {
114-
a,
115-
b,
116-
a_to_b: TransferState::Running(CopyBuffer::new()),
117-
b_to_a: TransferState::Running(CopyBuffer::new()),
118-
}
77+
let mut a_to_b = TransferState::Running(CopyBuffer::new());
78+
let mut b_to_a = TransferState::Running(CopyBuffer::new());
79+
poll_fn(|cx| {
80+
let a_to_b = transfer_one_direction(cx, &mut a_to_b, a, b)?;
81+
let b_to_a = transfer_one_direction(cx, &mut b_to_a, b, a)?;
82+
83+
// It is not a problem if ready! returns early because transfer_one_direction for the
84+
// other direction will keep returning TransferState::Done(count) in future calls to poll
85+
let a_to_b = ready!(a_to_b);
86+
let b_to_a = ready!(b_to_a);
87+
88+
Poll::Ready(Ok((a_to_b, b_to_a)))
89+
})
11990
.await
12091
}

0 commit comments

Comments
 (0)