#background-thread #stdin #default #non-blocking #fallback #streaming #immediate

bin+lib stdin-nonblocking

Dependency-less non-blocking stdin reader using background threads. Supports streaming and immediate fallback defaults.

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

Download history 154/week @ 2025-02-26 519/week @ 2025-03-05

673 downloads per month
Used in simd-r-drive

MIT license

10KB

Rust stdin Nonblocking

made-with-rust crates.io Documentation MIT licensed

OS Status
Ubuntu-latest Ubuntu Tests
macOS-latest macOS Tests
Windows-latest Windows Tests

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.

License

MIT License (c) 2025 Jeremy Harris.

No runtime deps