1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
doctest!;
use ;
use ;
use thread;
/// Spawns a background thread that continuously reads from stdin as a binary stream.
///
/// This function returns an `mpsc Receiver`, allowing non-blocking polling
/// of stdin input just like `spawn_stdin_channel`.
///
/// **Handling Interactive Mode:**
/// - If stdin is a terminal (interactive mode), this function immediately returns an empty receiver.
/// - This prevents blocking behavior when running interactively.
/// - When reading from a file or pipe, the background thread captures input **as raw bytes**.
///
/// # Returns
/// A `Receiver<Vec<u8>>` that emits **binary data** from stdin.
///
/// # Example
/// ```
/// use stdin_nonblocking::spawn_stdin_stream;
/// use std::sync::mpsc::TryRecvError;
/// use std::time::Duration;
///
/// 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));
/// }
/// ```
/// Reads stdin if available; otherwise, returns a default value.
///
/// This function intelligently determines whether to block:
/// - **Interactive Mode**: If stdin is a terminal, the function immediately returns the default without blocking.
/// - **Redirected Input**: If stdin is redirected from a file or pipe, it spawns a thread to read stdin and waits briefly (50ms).
/// - If data arrives promptly, it returns immediately.
/// - If no data is available within that short duration, it returns the provided default value.
///
/// # Arguments
/// * `default` - An optional fallback value returned if no input is available.
///
/// # Returns
/// * `Option<Vec<u8>>` - The stdin input if available, otherwise the provided default.
///
/// # Example
/// ```
/// use stdin_nonblocking::get_stdin_or_default;
///
/// let input = get_stdin_or_default(Some(b"fallback_value"));
///
/// assert_eq!(input, Some(b"fallback_value".to_vec()));
/// ```