7 unstable releases (3 breaking)
new 0.4.1 | Mar 13, 2025 |
---|---|
0.4.0 | Mar 11, 2025 |
0.3.0 | Mar 11, 2025 |
0.2.1 | Mar 4, 2025 |
0.1.0 | Mar 3, 2025 |
#246 in Concurrency
673 downloads per month
Used in simd-r-drive
10KB
Rust stdin
Nonblocking
OS | Status |
---|---|
Ubuntu-latest | |
macOS-latest | |
Windows-latest |
Dependency-less non-blocking stdin
reader using background threads. Supports streaming and immediate fallback defaults.
Supports binary data, streaming, and immediate fallback defaults.
Install
cargo add stdin-nonblocking
Usage
Get stdin
or Default
use stdin_nonblocking::get_stdin_or_default;
// If running in interactive mode (stdin is a terminal),
// `get_stdin_or_default` returns the default value immediately.
let input = get_stdin_or_default(Some(b"fallback_value"));
// Input is always `Vec<u8>`, ensuring binary safety.
assert_eq!(input, Some(b"fallback_value".to_vec()));
Read stdin
as Stream
use stdin_nonblocking::spawn_stdin_stream;
use std::sync::mpsc::TryRecvError;
use std::time::Duration;
// If running in interactive mode (stdin is a terminal),
// `spawn_stdin_stream` returns an empty receiver, meaning no input will be received.
let stdin_stream = spawn_stdin_stream();
loop {
match stdin_stream.try_recv() {
Ok(bytes) => println!("Received: {:?}", bytes), // Always raw bytes
Err(TryRecvError::Empty) => {
// No input yet; continue execution
}
Err(TryRecvError::Disconnected) => {
println!("Input stream closed. Exiting...");
break;
}
}
std::thread::sleep(Duration::from_millis(500));
}
Use with Tokio
Refer to the included Tokio Example App.
Related threads
- https://stackoverflow.com/questions/30012995/how-can-i-read-non-blocking-from-stdin
- https://www.reddit.com/r/rust/comments/fc71ju/how_to_read_from_stdin_without_blocking/?rdt=55515
License
MIT License (c) 2025 Jeremy Harris.