0.1.0 |
|
---|---|
0.1.0-alpha.1 |
|
#10 在 #compat
17KB
356 行
async-io-bridge
已废弃
请使用 tokio_util::io::SyncIoBridge
代替。
一个兼容包装器,围绕 std::io::{Read, Write, Seek}
实现 tokio::io::{AsyncRead, AsyncWrite, AsyncSeek}
.
如果您想将异步 io 对象包装以提供同步接口,请参阅 tokio-io-compat。
注意
永远不要在与原始 io 对象相同线程中消费包装的 io 对象,否则您将遇到死锁。
示例
use std::io::{Cursor, Read, Seek, SeekFrom, Write};
use async_io_bridge::BridgeBuilder;
let mut async_io = Cursor::new(vec![]); // some async io object
// Bridge all io traits you need.
let (fut, mut sync_io) = BridgeBuilder::new(async_io)
.bridge_read()
.bridge_write()
.bridge_seek()
.build();
// Spawn the bridge future to provide data to the sync io wrapper.
let bridge_handler = tokio::task::spawn(fut);
// Do anything you want with the sync io wrapper in a separate blocking thread.
let blocking_handler = tokio::task::spawn_blocking(move || {
sync_io.write_all(&[0, 1, 2, 3, 4]).unwrap();
sync_io.seek(SeekFrom::Start(2)).unwrap();
let mut buffer = [0; 1];
sync_io.read_exact(&mut buffer).unwrap();
assert_eq!(&buffer, &[2]);
});
blocking_handler.await.unwrap();
bridge_handler.await.unwrap();
依赖项
~2.4–4MB
~66K SLoC