diff --git a/Cargo.lock b/Cargo.lock index f960839..a4928ce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -214,7 +214,7 @@ dependencies = [ [[package]] name = "stdin-nonblocking" -version = "0.3.0" +version = "0.4.0" dependencies = [ "doc-comment", ] diff --git a/Cargo.toml b/Cargo.toml index b9c0475..ea7b417 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "stdin-nonblocking" -version = "0.3.0" +version = "0.4.0" authors = ["Jeremy Harris "] description = "Dependency-less non-blocking stdin reader using background threads. Supports streaming and immediate fallback defaults." repository = "https://github.com/jzombie/rust-stdin-nonblocking" diff --git a/README.md b/README.md index 53413f2..beddc8e 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ use stdin_nonblocking::get_stdin_or_default; let input = get_stdin_or_default(Some(b"fallback_value")); // Input is always `Vec`, ensuring binary safety. -assert_eq!(input, b"fallback_value".to_vec()); +assert_eq!(input, Some(b"fallback_value".to_vec())); ``` ### Read `stdin` as Stream diff --git a/src/bin/test_binary.rs b/src/bin/test_binary.rs index 776215c..b60930e 100644 --- a/src/bin/test_binary.rs +++ b/src/bin/test_binary.rs @@ -7,6 +7,6 @@ fn main() { // Print raw binary data instead of Debug format io::stdout() - .write_all(&input) + .write_all(&input.unwrap()) .expect("Failed to write output"); } diff --git a/src/lib.rs b/src/lib.rs index 9f3f1b5..9d9a822 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,6 @@ +#[cfg(doctest)] +doc_comment::doctest!("../README.md"); + use std::io::{self, IsTerminal, Read}; use std::sync::mpsc::{self, Receiver, Sender}; use std::thread; @@ -77,7 +80,7 @@ pub fn spawn_stdin_stream() -> Receiver> { /// * `default` - An optional fallback value returned if no input is available. /// /// # Returns -/// * `Vec` - The full stdin input (or default value as bytes). +/// * `Option>` - The full stdin input (or default value as bytes). /// /// # Example /// ``` @@ -85,18 +88,21 @@ pub fn spawn_stdin_stream() -> Receiver> { /// /// let input = get_stdin_or_default(Some(b"fallback_value")); /// -/// assert_eq!(input, b"fallback_value".to_vec()); +/// assert_eq!(input, Some(b"fallback_value".to_vec())); /// ``` -pub fn get_stdin_or_default(default: Option<&[u8]>) -> Vec { +pub fn get_stdin_or_default(default: Option<&[u8]>) -> Option> { let stdin_channel = spawn_stdin_stream(); // Give the reader thread a short time to capture any available input thread::sleep(Duration::from_millis(50)); if let Ok(data) = stdin_channel.try_recv() { - return data; + return Some(data); } + // Return `None` if no default + default?; + // No input available, return the default value - default.unwrap_or(b"").to_vec() + Some(default.unwrap_or(b"").to_vec()) }