-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
util/io: Add SyncIoBridge
#4146
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
14 commits
Select commit
Hold shift + click to select a range
919d827
util/io: Add `SyncIoBridge`
cgwalters ca04164
fix bounds
cgwalters 0b35775
update docs
cgwalters 2d5c9c8
forward more read methods
cgwalters 59a9566
Mention !Unpin types
cgwalters e6051a0
If an empty commit is pushed in the git tree, does the CI hear it?
cgwalters 29795db
Update tokio-util/src/io/sync_bridge.rs
cgwalters 541011b
Have `io` depend on `tokio/io-util` for SyncIoBridge
cgwalters 2d8b60c
Remove unncessary build constraint
cgwalters e7bab76
util: Create a new `io-util` feature that depends on `rt` and `io`
cgwalters 0a91e6d
util: We only need io-util macro if we have io
cgwalters 0584c03
Update tokio-util/Cargo.toml
cgwalters b8956f3
Merge branch 'master' into sync-io-bridge
cgwalters 2725071
Merge remote-tracking branch 'origin/master' into sync-io-bridge
cgwalters 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
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,103 @@ | ||
| use std::io::{Read, Write}; | ||
| use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; | ||
|
|
||
| /// Use a [`tokio::io::AsyncRead`] synchronously as a [`std::io::Read`] or | ||
| /// a [`tokio::io::AsyncWrite`] as a [`std::io::Write`]. | ||
| #[derive(Debug)] | ||
| pub struct SyncIoBridge<T> { | ||
| src: T, | ||
| rt: tokio::runtime::Handle, | ||
| } | ||
|
|
||
| impl<T: AsyncRead + Unpin> Read for SyncIoBridge<T> { | ||
| fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { | ||
| let src = &mut self.src; | ||
| self.rt.block_on(AsyncReadExt::read(src, buf)) | ||
| } | ||
|
|
||
| fn read_to_end(&mut self, buf: &mut Vec<u8>) -> std::io::Result<usize> { | ||
| let src = &mut self.src; | ||
| self.rt.block_on(src.read_to_end(buf)) | ||
| } | ||
|
|
||
| fn read_to_string(&mut self, buf: &mut String) -> std::io::Result<usize> { | ||
| let src = &mut self.src; | ||
| self.rt.block_on(src.read_to_string(buf)) | ||
| } | ||
|
|
||
| fn read_exact(&mut self, buf: &mut [u8]) -> std::io::Result<()> { | ||
| let src = &mut self.src; | ||
| // The AsyncRead trait returns the count, synchronous doesn't. | ||
| let _n = self.rt.block_on(src.read_exact(buf))?; | ||
| Ok(()) | ||
| } | ||
| } | ||
|
|
||
| impl<T: AsyncWrite + Unpin> Write for SyncIoBridge<T> { | ||
| fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { | ||
| let src = &mut self.src; | ||
| self.rt.block_on(src.write(buf)) | ||
| } | ||
|
|
||
|
cgwalters marked this conversation as resolved.
|
||
| fn flush(&mut self) -> std::io::Result<()> { | ||
| let src = &mut self.src; | ||
| self.rt.block_on(src.flush()) | ||
| } | ||
|
|
||
| fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> { | ||
| let src = &mut self.src; | ||
| self.rt.block_on(src.write_all(buf)) | ||
| } | ||
|
|
||
| fn write_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> std::io::Result<usize> { | ||
| let src = &mut self.src; | ||
| self.rt.block_on(src.write_vectored(bufs)) | ||
| } | ||
| } | ||
|
|
||
| // Because https://doc.rust-lang.org/std/io/trait.Write.html#method.is_write_vectored is at the time | ||
| // of this writing still unstable, we expose this as part of a standalone method. | ||
| impl<T: AsyncWrite> SyncIoBridge<T> { | ||
| /// Determines if the underlying [`tokio::io::AsyncWrite`] target supports efficient vectored writes. | ||
| /// | ||
| /// See [`tokio::io::AsyncWrite::is_write_vectored`]. | ||
| pub fn is_write_vectored(&self) -> bool { | ||
| self.src.is_write_vectored() | ||
| } | ||
| } | ||
|
|
||
| impl<T: Unpin> SyncIoBridge<T> { | ||
| /// Use a [`tokio::io::AsyncRead`] synchronously as a [`std::io::Read`] or | ||
| /// a [`tokio::io::AsyncWrite`] as a [`std::io::Write`]. | ||
| /// | ||
| /// When this struct is created, it captures a handle to the current thread's runtime with [`tokio::runtime::Handle::current`]. | ||
| /// It is hence OK to move this struct into a separate thread outside the runtime, as created | ||
| /// by e.g. [`tokio::task::spawn_blocking`]. | ||
| /// | ||
| /// Stated even more strongly: to make use of this bridge, you *must* move | ||
| /// it into a separate thread outside the runtime. The synchronous I/O will use the | ||
| /// underlying handle to block on the backing asynchronous source, via | ||
| /// [`tokio::runtime::Handle::block_on`]. As noted in the documentation for that | ||
| /// function, an attempt to `block_on` from an asynchronous execution context | ||
| /// will panic. | ||
| /// | ||
| /// # Wrapping `!Unpin` types | ||
| /// | ||
| /// Use e.g. `SyncIoBridge::new(Box::pin(src))`. | ||
| /// | ||
| /// # Panic | ||
| /// | ||
| /// This will panic if called outside the context of a Tokio runtime. | ||
| pub fn new(src: T) -> Self { | ||
|
cgwalters marked this conversation as resolved.
|
||
| Self::new_with_handle(src, tokio::runtime::Handle::current()) | ||
| } | ||
|
|
||
| /// Use a [`tokio::io::AsyncRead`] synchronously as a [`std::io::Read`] or | ||
| /// a [`tokio::io::AsyncWrite`] as a [`std::io::Write`]. | ||
| /// | ||
| /// This is the same as [`SyncIoBridge::new`], but allows passing an arbitrary handle and hence may | ||
| /// be initially invoked outside of an asynchronous context. | ||
| pub fn new_with_handle(src: T, rt: tokio::runtime::Handle) -> Self { | ||
| Self { src, rt } | ||
| } | ||
| } | ||
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,43 @@ | ||
| #![cfg(feature = "io-util")] | ||
|
|
||
| use std::error::Error; | ||
| use std::io::{Cursor, Read, Result as IoResult}; | ||
| use tokio::io::AsyncRead; | ||
| use tokio_util::io::SyncIoBridge; | ||
|
|
||
| async fn test_reader_len( | ||
| r: impl AsyncRead + Unpin + Send + 'static, | ||
| expected_len: usize, | ||
| ) -> IoResult<()> { | ||
| let mut r = SyncIoBridge::new(r); | ||
| let res = tokio::task::spawn_blocking(move || { | ||
| let mut buf = Vec::new(); | ||
| r.read_to_end(&mut buf)?; | ||
| Ok::<_, std::io::Error>(buf) | ||
| }) | ||
| .await?; | ||
| assert_eq!(res?.len(), expected_len); | ||
| Ok(()) | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn test_async_read_to_sync() -> Result<(), Box<dyn Error>> { | ||
| test_reader_len(tokio::io::empty(), 0).await?; | ||
| let buf = b"hello world"; | ||
| test_reader_len(Cursor::new(buf), buf.len()).await?; | ||
| Ok(()) | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn test_async_write_to_sync() -> Result<(), Box<dyn Error>> { | ||
| let mut dest = Vec::new(); | ||
| let src = b"hello world"; | ||
| let dest = tokio::task::spawn_blocking(move || -> Result<_, String> { | ||
| let mut w = SyncIoBridge::new(Cursor::new(&mut dest)); | ||
| std::io::copy(&mut Cursor::new(src), &mut w).map_err(|e| e.to_string())?; | ||
| Ok(dest) | ||
| }) | ||
| .await??; | ||
| assert_eq!(dest.as_slice(), src); | ||
| Ok(()) | ||
| } |
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.