|
| 1 | +#[cfg(doctest)] |
| 2 | +doc_comment::doctest!("../README.md"); |
| 3 | + |
1 | 4 | use std::io::{self, IsTerminal, Read}; |
2 | 5 | use std::sync::mpsc::{self, Receiver, Sender}; |
3 | 6 | use std::thread; |
@@ -77,26 +80,29 @@ pub fn spawn_stdin_stream() -> Receiver<Vec<u8>> { |
77 | 80 | /// * `default` - An optional fallback value returned if no input is available. |
78 | 81 | /// |
79 | 82 | /// # Returns |
80 | | -/// * `Vec<u8>` - The full stdin input (or default value as bytes). |
| 83 | +/// * `Option<Vec<u8>>` - The full stdin input (or default value as bytes). |
81 | 84 | /// |
82 | 85 | /// # Example |
83 | 86 | /// ``` |
84 | 87 | /// use stdin_nonblocking::get_stdin_or_default; |
85 | 88 | /// |
86 | 89 | /// let input = get_stdin_or_default(Some(b"fallback_value")); |
87 | 90 | /// |
88 | | -/// assert_eq!(input, b"fallback_value".to_vec()); |
| 91 | +/// assert_eq!(input, Some(b"fallback_value".to_vec())); |
89 | 92 | /// ``` |
90 | | -pub fn get_stdin_or_default(default: Option<&[u8]>) -> Vec<u8> { |
| 93 | +pub fn get_stdin_or_default(default: Option<&[u8]>) -> Option<Vec<u8>> { |
91 | 94 | let stdin_channel = spawn_stdin_stream(); |
92 | 95 |
|
93 | 96 | // Give the reader thread a short time to capture any available input |
94 | 97 | thread::sleep(Duration::from_millis(50)); |
95 | 98 |
|
96 | 99 | if let Ok(data) = stdin_channel.try_recv() { |
97 | | - return data; |
| 100 | + return Some(data); |
98 | 101 | } |
99 | 102 |
|
| 103 | + // Return `None` if no default |
| 104 | + default?; |
| 105 | + |
100 | 106 | // No input available, return the default value |
101 | | - default.unwrap_or(b"").to_vec() |
| 107 | + Some(default.unwrap_or(b"").to_vec()) |
102 | 108 | } |
0 commit comments