Skip to content

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

License

Notifications You must be signed in to change notification settings

jzombie/rust-stdin-nonblocking

Repository files navigation

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.

Related threads

License

MIT License (c) 2025 Jeremy Harris.

About

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

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages