-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
io: add tokio_util::io::simplex
#7565
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
Open
ADD-SP
wants to merge
22
commits into
tokio-rs:master
Choose a base branch
from
ADD-SP:add_sp/io-alt-simplex
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
43805ab
io: add `tokio_util::io::simplex`
ADD-SP b631600
merge: sync changes from the base branch
ADD-SP 0274aed
merge: sync changes from the base branch
ADD-SP 5b8b019
io: unlock before waking up
ADD-SP afc7e07
io: make `Inner::with_capacity` more "with_capacity"
ADD-SP 4ffa045
merge: sync changes from the base branch
ADD-SP 585a957
do not include `tokio/rt` by default
ADD-SP f6fc30a
panics on zero capacity
ADD-SP 41665dc
poll_shutdown should be called multiple times without error
ADD-SP 6eafcd1
wake up the receiver on shutdown
ADD-SP 95837ba
wake up the receiver after dropping the sender
ADD-SP d7f6d20
wake up the sender after dropping the receiver
ADD-SP 1e30455
fix hang forever issues
ADD-SP 53c6d81
unify the error message
ADD-SP 6eb9659
add more tests
ADD-SP 2225999
merge: sync changes from the base branch
ADD-SP 45976a9
support poll_write_vectored
ADD-SP d35012b
fix typos
ADD-SP d9809a8
adopt coop for poll_write_vectored
ADD-SP 439a4aa
merge: sync changes from the base branch
ADD-SP f954e93
fix rustfmt reports
ADD-SP 34e3a42
merge: sync changes from the base branch
ADD-SP 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
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,322 @@ | ||
| //! Unidirectional byte-oriented channel. | ||
|
|
||
| use crate::util::poll_proceed_and_make_progress; | ||
|
|
||
| use bytes::Buf; | ||
| use bytes::BytesMut; | ||
| use futures_core::ready; | ||
| use std::io::Error as IoError; | ||
| use std::io::ErrorKind as IoErrorKind; | ||
| use std::io::IoSlice; | ||
| use std::pin::Pin; | ||
| use std::sync::{Arc, Mutex}; | ||
| use std::task::{Context, Poll, Waker}; | ||
| use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; | ||
|
|
||
| type IoResult<T> = Result<T, IoError>; | ||
|
|
||
| const CLOSED_ERROR_MSG: &str = "simplex has been closed"; | ||
|
|
||
| #[derive(Debug)] | ||
| struct Inner { | ||
| /// `poll_write` will return [`Poll::Pending`] if the backpressure boundary is reached | ||
| backpressure_boundary: usize, | ||
|
|
||
| /// either [`Sender`] or [`Receiver`] is closed | ||
| is_closed: bool, | ||
|
|
||
| /// Waker used to wake the [`Receiver`] | ||
| receiver_waker: Option<Waker>, | ||
|
|
||
| /// Waker used to wake the [`Sender`] | ||
| sender_waker: Option<Waker>, | ||
|
|
||
| /// Buffer used to read and write data | ||
| buf: BytesMut, | ||
| } | ||
|
|
||
| impl Inner { | ||
| fn with_capacity(capacity: usize) -> Self { | ||
| Self { | ||
| backpressure_boundary: capacity, | ||
| is_closed: false, | ||
| receiver_waker: None, | ||
| sender_waker: None, | ||
| buf: BytesMut::with_capacity(capacity), | ||
| } | ||
| } | ||
|
|
||
| fn register_receiver_waker(&mut self, waker: &Waker) { | ||
| match self.receiver_waker.as_mut() { | ||
| Some(old) if old.will_wake(waker) => {} | ||
| Some(old) => old.clone_from(waker), | ||
| None => self.receiver_waker = Some(waker.clone()), | ||
| } | ||
| } | ||
|
|
||
| fn register_sender_waker(&mut self, waker: &Waker) { | ||
| match self.sender_waker.as_mut() { | ||
| Some(old) if old.will_wake(waker) => {} | ||
| Some(old) => old.clone_from(waker), | ||
| None => self.sender_waker = Some(waker.clone()), | ||
| } | ||
| } | ||
|
|
||
| fn take_receiver_waker(&mut self) -> Option<Waker> { | ||
| self.receiver_waker.take() | ||
| } | ||
|
|
||
| fn take_sender_waker(&mut self) -> Option<Waker> { | ||
| self.sender_waker.take() | ||
| } | ||
|
|
||
| fn is_closed(&self) -> bool { | ||
| self.is_closed | ||
| } | ||
|
|
||
| fn close_receiver(&mut self) -> Option<Waker> { | ||
| self.is_closed = true; | ||
| self.take_sender_waker() | ||
| } | ||
|
|
||
| fn close_sender(&mut self) -> Option<Waker> { | ||
| self.is_closed = true; | ||
| self.take_receiver_waker() | ||
| } | ||
| } | ||
|
|
||
| /// Receiver of the simplex channel. | ||
| /// | ||
| /// You can still read the remaining data from the buffer | ||
| /// even if the write half has been dropped. | ||
| /// See [`Sender::poll_shutdown`] and [`Sender::drop`] for more details. | ||
| #[derive(Debug)] | ||
| pub struct Receiver { | ||
| inner: Arc<Mutex<Inner>>, | ||
| } | ||
|
|
||
| impl Drop for Receiver { | ||
| /// This also wakes up the [`Sender`]. | ||
| fn drop(&mut self) { | ||
| let maybe_waker = { | ||
| let mut inner = self.inner.lock().unwrap(); | ||
| inner.close_receiver() | ||
| }; | ||
|
|
||
| if let Some(waker) = maybe_waker { | ||
| waker.wake(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl AsyncRead for Receiver { | ||
| fn poll_read( | ||
| self: Pin<&mut Self>, | ||
| cx: &mut Context<'_>, | ||
| buf: &mut ReadBuf<'_>, | ||
| ) -> Poll<IoResult<()>> { | ||
| let mut inner = self.inner.lock().unwrap(); | ||
|
|
||
| let to_read = buf.remaining().min(inner.buf.remaining()); | ||
| if to_read == 0 { | ||
| if inner.is_closed() || buf.remaining() == 0 { | ||
| return Poll::Ready(Ok(())); | ||
| } | ||
|
|
||
| inner.register_receiver_waker(cx.waker()); | ||
| let maybe_waker = inner.take_sender_waker(); | ||
| drop(inner); // unlock before waking up | ||
| if let Some(waker) = maybe_waker { | ||
| waker.wake(); | ||
| } | ||
| return Poll::Pending; | ||
| } | ||
|
|
||
| ready!(poll_proceed_and_make_progress(cx)); | ||
|
|
||
| buf.put_slice(&inner.buf[..to_read]); | ||
| inner.buf.advance(to_read); | ||
| let waker = inner.take_sender_waker(); | ||
| drop(inner); // unlock before waking up | ||
| if let Some(waker) = waker { | ||
| waker.wake(); | ||
| } | ||
| Poll::Ready(Ok(())) | ||
| } | ||
| } | ||
|
|
||
| /// Sender of the simplex channel. | ||
| /// | ||
| /// ## Shutdown | ||
| /// | ||
| /// See [`Sender::poll_shutdown`]. | ||
| #[derive(Debug)] | ||
| pub struct Sender { | ||
| inner: Arc<Mutex<Inner>>, | ||
| } | ||
|
|
||
| impl Drop for Sender { | ||
| /// This also wakes up the [`Receiver`]. | ||
| fn drop(&mut self) { | ||
| let maybe_waker = { | ||
| let mut inner = self.inner.lock().unwrap(); | ||
| inner.close_sender() | ||
| }; | ||
|
|
||
| if let Some(waker) = maybe_waker { | ||
| waker.wake(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl AsyncWrite for Sender { | ||
| /// # Errors | ||
| /// | ||
| /// This method will return [`IoErrorKind::BrokenPipe`] | ||
| /// if the channel has been closed. | ||
| fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<IoResult<usize>> { | ||
| let mut inner = self.inner.lock().unwrap(); | ||
|
|
||
| if inner.is_closed() { | ||
| return Poll::Ready(Err(IoError::new(IoErrorKind::BrokenPipe, CLOSED_ERROR_MSG))); | ||
| } | ||
|
|
||
| let free = inner | ||
| .backpressure_boundary | ||
| .checked_sub(inner.buf.len()) | ||
| .expect("backpressure boundary overflow"); | ||
| let to_write = buf.len().min(free); | ||
ADD-SP marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if to_write == 0 { | ||
| if buf.is_empty() { | ||
| return Poll::Ready(Ok(0)); | ||
| } | ||
|
|
||
| inner.register_sender_waker(cx.waker()); | ||
| let waker = inner.take_receiver_waker(); | ||
| drop(inner); // unlock before waking up | ||
| if let Some(waker) = waker { | ||
| waker.wake(); | ||
| } | ||
| return Poll::Pending; | ||
| } | ||
|
|
||
| // this is to avoid starving other tasks | ||
| ready!(poll_proceed_and_make_progress(cx)); | ||
|
|
||
| inner.buf.extend_from_slice(&buf[..to_write]); | ||
| let waker = inner.take_receiver_waker(); | ||
| drop(inner); // unlock before waking up | ||
| if let Some(waker) = waker { | ||
| waker.wake(); | ||
| } | ||
| Poll::Ready(Ok(to_write)) | ||
| } | ||
|
|
||
| /// # Errors | ||
| /// | ||
| /// This method will return [`IoErrorKind::BrokenPipe`] | ||
| /// if the channel has been closed. | ||
| fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<IoResult<()>> { | ||
| let inner = self.inner.lock().unwrap(); | ||
| if inner.is_closed() { | ||
| Poll::Ready(Err(IoError::new(IoErrorKind::BrokenPipe, CLOSED_ERROR_MSG))) | ||
| } else { | ||
| Poll::Ready(Ok(())) | ||
| } | ||
| } | ||
|
|
||
| /// After returns [`Poll::Ready`], all the following call to | ||
| /// [`Sender::poll_write`] and [`Sender::poll_flush`] | ||
| /// will return error. | ||
| /// | ||
| /// The [`Receiver`] can still be used to read remaining data | ||
| /// until all bytes have been consumed. | ||
| fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<IoResult<()>> { | ||
| let maybe_waker = { | ||
| let mut inner = self.inner.lock().unwrap(); | ||
| inner.close_sender() | ||
| }; | ||
|
|
||
| if let Some(waker) = maybe_waker { | ||
| waker.wake(); | ||
| } | ||
|
|
||
| Poll::Ready(Ok(())) | ||
| } | ||
|
|
||
| fn is_write_vectored(&self) -> bool { | ||
| true | ||
| } | ||
|
|
||
| fn poll_write_vectored( | ||
| self: Pin<&mut Self>, | ||
| cx: &mut Context<'_>, | ||
| bufs: &[IoSlice<'_>], | ||
| ) -> Poll<Result<usize, IoError>> { | ||
| let mut inner = self.inner.lock().unwrap(); | ||
| if inner.is_closed() { | ||
| return Poll::Ready(Err(IoError::new(IoErrorKind::BrokenPipe, CLOSED_ERROR_MSG))); | ||
| } | ||
|
|
||
martin-g marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| let free = inner | ||
| .backpressure_boundary | ||
| .checked_sub(inner.buf.len()) | ||
| .expect("backpressure boundary overflow"); | ||
| if free == 0 { | ||
| inner.register_sender_waker(cx.waker()); | ||
| let maybe_waker = inner.take_receiver_waker(); | ||
| drop(inner); // unlock before waking up | ||
| if let Some(waker) = maybe_waker { | ||
| waker.wake(); | ||
| } | ||
| return Poll::Pending; | ||
| } | ||
|
|
||
ADD-SP marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ready!(poll_proceed_and_make_progress(cx)); | ||
|
|
||
| let mut rem = free; | ||
| for buf in bufs { | ||
| if rem == 0 { | ||
| break; | ||
| } | ||
|
|
||
| let to_write = buf.len().min(rem); | ||
| if to_write == 0 { | ||
| assert_ne!(rem, 0); | ||
| assert_eq!(buf.len(), 0); | ||
| continue; | ||
| } | ||
|
|
||
| inner.buf.extend_from_slice(&buf[..to_write]); | ||
| rem -= to_write; | ||
| } | ||
|
|
||
| let waker = inner.take_receiver_waker(); | ||
| drop(inner); // unlock before waking up | ||
| if let Some(waker) = waker { | ||
| waker.wake(); | ||
| } | ||
|
|
||
| Poll::Ready(Ok(free - rem)) | ||
| } | ||
| } | ||
|
|
||
| /// Create a simplex channel. | ||
| /// | ||
| /// The `capacity` parameter specifies the maximum number of bytes that can be | ||
| /// stored in the channel without making the [`Sender::poll_write`] | ||
| /// return [`Poll::Pending`]. | ||
| /// | ||
| /// # Panics | ||
| /// | ||
| /// This function will panic if `capacity` is zero. | ||
| pub fn new(capacity: usize) -> (Sender, Receiver) { | ||
ADD-SP marked this conversation as resolved.
Show resolved
Hide resolved
ADD-SP marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| assert_ne!(capacity, 0, "capacity must be greater than zero"); | ||
|
|
||
| let inner = Arc::new(Mutex::new(Inner::with_capacity(capacity))); | ||
| let tx = Sender { | ||
| inner: Arc::clone(&inner), | ||
| }; | ||
| let rx = Receiver { inner }; | ||
| (tx, rx) | ||
| } | ||
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
Oops, something went wrong.
Oops, something went wrong.
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.