2个不稳定版本
0.3.0 | 2021年1月20日 |
---|---|
0.2.0 | 2021年1月5日 |
#1050 in 异步
用于 xenopeltis
9KB
109 行
termion-input-tokio
一个适配器,将termion的输入和按键事件迭代器暴露为异步流。
兼容性
与Tokio v1.0兼容。
用法
use futures::StreamExt;
use std::future;
use termion::{event::Key, raw::IntoRawMode};
use termion_input_tokio::TermReadAsync;
#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
// Disable line buffering, local echo, etc.
let _raw_term = std::io::stdout().into_raw_mode()?;
tokio::io::stdin()
.keys_stream()
// End the stream when 'q' is pressed.
.take_while(|event| {
future::ready(match event {
Ok(Key::Char('q')) => false,
_ => true,
})
})
// Print each key that was pressed.
.for_each(|event| async move {
println!("{:?}\r", event);
})
.await;
Ok(())
}
非阻塞输入
在stdin
中使用真正的非阻塞读取是具有挑战性的。在常见情况下,stdin
和stdout
都指向相同的文件,通常是PTY。由于非阻塞模式是每个文件的属性,而不是每个文件描述符的属性,使用fcntl
和O_NONBLOCK
来将stdin
变为非阻塞模式也将使stdout
变为非阻塞。由于大多数代码在向stdout
写入时没有准备好处理EWOULDBLOCK
,因此通常使用阻塞操作在辅助线程上执行异步读取。这就是tokio::io::stdin()实现的AsyncRead
的方式。
致谢
这是基于Kayo Phoenix的termion-tokio,它又基于termion中的代码。
依赖项
~3.5–4.5MB
~75K SLoC