-
Notifications
You must be signed in to change notification settings - Fork 662
Create copy_buf_abortable, which enables to stop copying in the middle. #2507
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
7b372fe
Create copy_buf_abortable, which allows stopping copying in the middle.
kazuki0824 9e9ae28
Add mod copy_buf_abortable
kazuki0824 4b4b913
fix docs
kazuki0824 4208c26
fix docs
kazuki0824 362ed8c
Remove unnecessary wakeups and flag checking
kazuki0824 8716882
Register the waker
kazuki0824 f9a0139
Use this for pinned structs instead of self
kazuki0824 e49bf7d
Add checks for the aborted flag
kazuki0824 9f96599
Remove is_aborted and insert in line L119
kazuki0824 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,124 @@ | ||
use crate::abortable::{AbortHandle, AbortInner, Aborted}; | ||
use futures_core::future::Future; | ||
use futures_core::task::{Context, Poll}; | ||
use futures_io::{AsyncBufRead, AsyncWrite}; | ||
use pin_project_lite::pin_project; | ||
use std::io; | ||
use std::pin::Pin; | ||
use std::sync::atomic::Ordering; | ||
use std::sync::Arc; | ||
|
||
/// Creates a future which copies all the bytes from one object to another, with its `AbortHandle`. | ||
/// | ||
/// The returned future will copy all the bytes read from this `AsyncBufRead` into the | ||
/// `writer` specified. This future will only complete once abort has been requested or the `reader` has hit | ||
/// EOF and all bytes have been written to and flushed from the `writer` | ||
/// provided. | ||
/// | ||
/// On success the number of bytes is returned. If aborted, `Aborted` is returned. Otherwise, the underlying error is returned. | ||
/// | ||
/// # Examples | ||
/// | ||
/// ``` | ||
/// # futures::executor::block_on(async { | ||
/// use futures::io::{self, AsyncWriteExt, Cursor}; | ||
/// use futures::future::Aborted; | ||
/// | ||
/// let reader = Cursor::new([1, 2, 3, 4]); | ||
/// let mut writer = Cursor::new(vec![0u8; 5]); | ||
/// | ||
/// let (fut, abort_handle) = io::copy_buf_abortable(reader, &mut writer); | ||
/// let bytes = fut.await; | ||
/// abort_handle.abort(); | ||
/// writer.close().await.unwrap(); | ||
/// match bytes { | ||
/// Ok(Ok(n)) => { | ||
/// assert_eq!(n, 4); | ||
/// assert_eq!(writer.into_inner(), [1, 2, 3, 4, 0]); | ||
/// Ok(n) | ||
/// }, | ||
/// Ok(Err(a)) => { | ||
/// Err::<u64, Aborted>(a) | ||
/// } | ||
/// Err(e) => panic!("{}", e) | ||
/// } | ||
/// # }).unwrap(); | ||
/// ``` | ||
pub fn copy_buf_abortable<R, W>( | ||
reader: R, | ||
writer: &mut W, | ||
) -> (CopyBufAbortable<'_, R, W>, AbortHandle) | ||
where | ||
R: AsyncBufRead, | ||
W: AsyncWrite + Unpin + ?Sized, | ||
{ | ||
let (handle, reg) = AbortHandle::new_pair(); | ||
(CopyBufAbortable { reader, writer, amt: 0, inner: reg.inner }, handle) | ||
} | ||
|
||
pin_project! { | ||
/// Future for the [`copy_buf()`] function. | ||
#[derive(Debug)] | ||
#[must_use = "futures do nothing unless you `.await` or poll them"] | ||
pub struct CopyBufAbortable<'a, R, W: ?Sized> { | ||
#[pin] | ||
reader: R, | ||
writer: &'a mut W, | ||
amt: u64, | ||
inner: Arc<AbortInner> | ||
} | ||
} | ||
|
||
macro_rules! ready_or_break { | ||
($e:expr $(,)?) => { | ||
match $e { | ||
$crate::task::Poll::Ready(t) => t, | ||
$crate::task::Poll::Pending => break, | ||
} | ||
}; | ||
} | ||
|
||
impl<R, W> Future for CopyBufAbortable<'_, R, W> | ||
where | ||
R: AsyncBufRead, | ||
W: AsyncWrite + Unpin + Sized, | ||
{ | ||
type Output = Result<Result<u64, Aborted>, io::Error>; | ||
|
||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { | ||
let mut this = self.project(); | ||
loop { | ||
// Check if the task has been aborted | ||
if this.inner.aborted.load(Ordering::Relaxed) { | ||
return Poll::Ready(Ok(Err(Aborted))); | ||
} | ||
|
||
// Read some bytes from the reader, and if we have reached EOF, return total bytes read | ||
let buffer = ready_or_break!(this.reader.as_mut().poll_fill_buf(cx))?; | ||
if buffer.is_empty() { | ||
ready_or_break!(Pin::new(&mut this.writer).poll_flush(cx))?; | ||
return Poll::Ready(Ok(Ok(*this.amt))); | ||
} | ||
|
||
// Pass the buffer to the writer, and update the amount written | ||
let i = ready_or_break!(Pin::new(&mut this.writer).poll_write(cx, buffer))?; | ||
if i == 0 { | ||
return Poll::Ready(Err(io::ErrorKind::WriteZero.into())); | ||
} | ||
*this.amt += i as u64; | ||
this.reader.as_mut().consume(i); | ||
} | ||
// Schedule the task to be woken up again. | ||
// Never called unless Poll::Pending is returned from io objects. | ||
this.inner.waker.register(cx.waker()); | ||
|
||
// Check to see if the task was aborted between the first check and | ||
// registration. | ||
// Checking with `Relaxed` is sufficient because | ||
// `register` introduces an `AcqRel` barrier. | ||
if this.inner.aborted.load(Ordering::Relaxed) { | ||
return Poll::Ready(Ok(Err(Aborted))); | ||
} | ||
Poll::Pending | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.