Skip to main content

rumtk_core/
cli.rs

1/*
2 * rumtk attempts to implement HL7 and medical protocols for interoperability in medicine.
3 * This toolkit aims to be reliable, simple, performant, and standards compliant.
4 * Copyright (C) 2025  Luis M. Santos, M.D. <lsantos@medicalmasses.com>
5 * Copyright (C) 2025  MedicalMasses L.L.C. <contact@medicalmasses.com>
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19 */
20
21///
22/// Tools for handling reading and writing from the standard I/O/E.
23///
24/// Per this [stackoverflow discussion](https://unix.stackexchange.com/questions/37508/in-what-order-do-piped-commands-run).
25/// Note:
26///```text
27///  Piped commands run concurrently. When you run ps | grep …, it's the luck of the draw (or a matter of details of the workings of the shell combined with scheduler fine-tuning deep in the bowels of the kernel) as to whether ps or grep starts first, and in any case they continue to execute concurrently.
28///
29///  This is very commonly used to allow the second program to process data as it comes out from the first program, before the first program has completed its operation. For example
30///
31///  grep pattern very-large-file | tr a-z A-Z
32///  begins to display the matching lines in uppercase even before grep has finished traversing the large file.
33///
34///  grep pattern very-large-file | head -n 1
35///  displays the first matching line, and may stop processing well before grep has finished reading its input file.
36///
37///  If you read somewhere that piped programs run in sequence, flee this document. Piped programs run concurrently and always have.
38/// ```
39///
40/// I bring the note above because that was my original understanding, but I have had to spend a
41/// crazy amount of time trying to get data flowing from one process to another without the initial
42/// process first exiting.
43///
44pub mod cli_utils {
45    use crate::base::{RUMResult, RUMVec};
46    use crate::cpu::CPU_PAGE_SIZE;
47    use crate::strings::rumtk_format;
48    use std::io::{stdin, stdout, BufWriter, Read, Write};
49    use std::os::fd::{AsRawFd, FromRawFd};
50
51    const STD_IN_STEP_SIZE: usize = u16::MAX as usize;
52
53    pub type BufferSlice = Vec<u8>;
54    pub type BufferChunk = [u8; STD_IN_STEP_SIZE];
55
56    ///
57    /// Consumes the incoming buffer in chunks of [CPU_PAGE_SIZE](CPU_PAGE_SIZE) bytes size
58    /// until no more bytes are present.
59    ///
60    /// To avoid calling a blocking read, we check if the read yielded an amount of bytes fewer than
61    /// the requested chunk size.
62    ///
63    /// ## Example
64    ///
65    /// ```
66    /// use rumtk_core::cli::cli_utils::{read_stdin};
67    /// use rumtk_core::cpu::CPU_PAGE_SIZE;
68    ///
69    /// let stdin_data = read_stdin(CPU_PAGE_SIZE).unwrap();
70    ///
71    /// assert_eq!(stdin_data.len(), 0, "Returned data with {} size even though we expected 0 bytes!", stdin_data.len())
72    /// ```
73    ///
74    pub fn read_stdin(minimum_size: usize) -> RUMResult<RUMVec<u8>> {
75        let mut stdin_buffer = RUMVec::with_capacity(minimum_size);
76
77        loop {
78            let s = read_some_stdin(&mut stdin_buffer)?;
79
80            // If we attempt the next read, it is likely to be a 0 byte read. Why does this matter?
81            // Well, if the other end of the pipe is still open, the read call will stall in Rust's
82            // std and it is because it expects EOF but that never comes.
83            // If you look at https://man7.org/linux/man-pages/man2/read.2.html, read should return
84            // 0 and simply let us naturally break, but a read < than requested buffer appears to be
85            // an equally valid way to handle terminal and piped data.
86            // We have to check against 0 because the more optimal the buffer size we ask for (e.g.
87            // larger reads for minimum syscall time) the less likely the kernel is ready with the
88            // requested data.
89
90            // Example reads at u16::Max
91            // Read 65535 bytes
92            // Read 61441 bytes
93            // Read 65535 bytes
94            // Read 61441 bytes
95            // Read 8192 bytes
96            // Read 65535 bytes
97            // Read 61441 bytes
98            // Read 65535 bytes
99            // Read 61441 bytes
100            // Read 8192 bytes
101            // Read 65535 bytes
102            // Read 61441 bytes
103            // Read 65535 bytes
104            // Read 61441 bytes
105            // Read 8192 bytes
106            // Read 65535 bytes
107            // Read 61441 bytes
108            // Read 65535 bytes
109            // Read 61441 bytes
110            // Read 8192 bytes
111            // Read 65535 bytes
112            // Read 61441 bytes
113            // Read 65535 bytes
114            // Read 61441 bytes
115            // Read 8192 bytes
116            // Read 65535 bytes
117            // Read 61441 bytes
118            // Read 65535 bytes
119            // Read 61441 bytes
120            // Read 8192 bytes
121            // Read 65535 bytes
122            // Read 61441 bytes
123            // Read 65535 bytes
124            // Read 61441 bytes
125            // Read 8192 bytes
126            // Read 65535 bytes
127            // Read 61441 bytes
128            // Read 65535 bytes
129            // Read 61441 bytes
130            // Read 8192 bytes
131            // Read 65535 bytes
132            // Read 61441 bytes
133            // Read 65535 bytes
134            // Read 41974 bytes
135            // Read 0 bytes
136            // Total: 2331637 => 2.2MB
137            if s == 0 {
138                break;
139            }
140        }
141
142        Ok(stdin_buffer)
143    }
144
145    ///
146    /// Consumes the incoming buffer in chunks of [CPU_SIMD_64_SIZE](crate::cpu::CPU_SIMD_64_SIZE) bytes size.
147    ///
148    /// ## Example
149    ///
150    /// ```
151    /// use std::io::stdin;
152    /// use std::io::prelude::*;
153    /// use std::process::{Command, Stdio};
154    /// use rumtk_core::cli::cli_utils::{read_some_stdin};
155    /// use rumtk_core::cpu::CPU_PAGE_SIZE;
156    /// use rumtk_core::base::RUMVec;
157    ///
158    /// let mut stdin_buffer = RUMVec::with_capacity(CPU_PAGE_SIZE);
159    /// let mut s = read_some_stdin(&mut stdin_buffer).unwrap();
160    /// let mut totas_s = s;
161    /// while s > 0 {
162    ///    s = read_some_stdin(&mut stdin_buffer).unwrap();
163    ///    totas_s += s;
164    /// }
165    ///
166    /// assert_eq!(totas_s, 0, "Returned data with {} size even though we expected 0 bytes!", totas_s)
167    /// ```
168    ///
169    #[inline]
170    pub fn read_some_stdin(buf: &mut BufferSlice) -> RUMResult<usize> {
171        let mut chunk: BufferChunk = [0; STD_IN_STEP_SIZE];
172
173        match stdin().read(&mut chunk[..]) {
174            Ok(s) => {
175                buf.extend_from_slice(&chunk[..s]);
176                Ok(s)
177            }
178            Err(e) => Err(rumtk_format!("Error reading stdin chunk because {}!", e)),
179        }
180    }
181
182    ///
183    /// writes [`stringview`] to `stdout`.
184    ///
185    pub fn write_string_stdout(data: &str) -> RUMResult<()> {
186        write_stdout(&data.as_bytes())
187    }
188
189    ///
190    /// Writes [RUMBuffer] to `stdout`.
191    ///
192    #[cfg(target_os = "windows")]
193    pub fn write_stdout(data: &[u8]) -> RUMResult<()> {
194        match stdout().write_all(data) {
195            Ok(_) => {}
196            Err(e) => return Err(rumtk_format!("Error writing to stdout because => {}", e)),
197        };
198        flush_stdout()?;
199        Ok(())
200    }
201
202    #[cfg(any(target_os = "unix", target_os = "linux", target_os = "macos"))]
203    pub fn write_stdout(data: &[u8]) -> RUMResult<()> {
204        // Create an unbuffered File handle from file descriptor 1 (stdout)
205        let stdout_fd = stdout().as_raw_fd();
206
207        {
208            let mut file = BufWriter::new(unsafe { std::fs::File::from_raw_fd(stdout_fd) });
209
210            // Write bytes directly
211            match file.write_all(data) {
212                Ok(_) => {
213                    file.flush().unwrap_or_default();
214                    std::mem::forget(file);
215                },
216                Err(e) => return Err(rumtk_format!("Error writing to stdout because {}", e)),
217            };
218        }
219
220        flush_stdout()?;
221        Ok(())
222    }
223
224    fn flush_stdout() -> RUMResult<()> {
225        match stdout().flush() {
226            Ok(_) => Ok(()),
227            Err(e) => Err(rumtk_format!("Error flushing stdout because => {}", e)),
228        }
229    }
230
231    pub fn print_license_notice(program: &str, year: &str, author_list: &Vec<&str>) {
232        let authors = author_list.join(", ");
233        let notice = rumtk_format!(
234            r"  {program}  Copyright (C) {year}  {authors}
235                This program comes with ABSOLUTELY NO WARRANTY.
236                This is free software, and you are welcome to redistribute it
237                under certain conditions."
238        );
239        eprintln!("{}", notice);
240    }
241}
242
243pub mod macros {
244    ///
245    /// Reads STDIN and unescapes the incoming message.
246    /// Return this unescaped message.
247    ///
248    /// # Example
249    ///
250    /// ## Without specifying the minimum read size.
251    /// ```
252    /// use rumtk_core::base::{RUMResult, RUMVec};
253    /// use rumtk_core::buffers::*;
254    /// use rumtk_core::rumtk_read_stdin;
255    ///
256    /// fn test_read_stdin() -> RUMResult<RUMVec<u8>> {
257    ///     rumtk_read_stdin!()
258    /// }
259    ///
260    /// match test_read_stdin() {
261    ///     Ok(s) => (),
262    ///     Err(e) => panic!("Error reading stdin because => {}", e)
263    /// }
264    /// ```
265    ///
266    /// ## With specifying the minimum read size.
267    /// ```
268    /// use rumtk_core::base::{RUMResult, RUMVec};
269    /// use rumtk_core::buffers::*;
270    /// use rumtk_core::rumtk_read_stdin;
271    ///
272    /// fn test_read_stdin() -> RUMResult<RUMVec<u8>> {
273    ///     rumtk_read_stdin!(1024)
274    /// }
275    ///
276    /// match test_read_stdin() {
277    ///     Ok(s) => (),
278    ///     Err(e) => panic!("Error reading stdin because => {}", e)
279    /// }
280    /// ```
281    ///
282    #[macro_export]
283    macro_rules! rumtk_read_stdin {
284        (  ) => {{
285            use $crate::cpu::CPU_PAGE_SIZE;
286            use $crate::cli::cli_utils::{read_stdin};
287            read_stdin(CPU_PAGE_SIZE * CPU_PAGE_SIZE)
288        }};
289        ( $min_expected_size:expr ) => {{
290            use $crate::cli::cli_utils::{read_stdin};
291            read_stdin($min_expected_size)
292        }};
293    }
294
295    ///
296    /// Writes [RUMString](crate::strings::RUMString) or [RUMBuffer](crate::types::RUMBuffer) to `stdout`.
297    ///
298    /// If the `binary` parameter is passed, we push the `message` parameter directly to `stdout`. the
299    /// `message` parameter has to be of type [RUMBuffer](crate::types::RUMBuffer).
300    ///
301    /// ## Example
302    ///
303    /// ### Default / Pushing a String
304    /// ```
305    /// use rumtk_core::rumtk_write_stdout;
306    ///
307    /// rumtk_write_stdout!("I ❤ my wife!");
308    /// ```
309    ///
310    /// ## Pushing Binary Buffer
311    /// ```
312    /// use rumtk_core::rumtk_write_stdout;
313    /// use rumtk_core::buffers::{new_random_rumbuffer, DEFAULT_BUFFER_CHUNK_SIZE};
314    ///
315    /// let buffer = new_random_rumbuffer::<DEFAULT_BUFFER_CHUNK_SIZE>();
316    /// rumtk_write_stdout!(buffer, true);
317    /// ```
318    ///
319    #[macro_export]
320    macro_rules! rumtk_write_stdout {
321        ( $message:expr ) => {{
322            use $crate::cli::cli_utils::write_string_stdout;
323            write_string_stdout(&$message)
324        }};
325        ( $message:expr, $binary:expr ) => {{
326            use $crate::cli::cli_utils::write_stdout;
327            write_stdout(&$message)
328        }};
329    }
330
331    ///
332    /// Prints the mandatory GPL License Notice to terminal!
333    ///
334    /// # Example
335    /// ## Default
336    /// ```
337    /// use rumtk_core::rumtk_print_license_notice;
338    ///
339    /// rumtk_print_license_notice!();
340    /// ```
341    /// ## Program Only
342    /// ```
343    /// use rumtk_core::rumtk_print_license_notice;
344    ///
345    /// rumtk_print_license_notice!("RUMTK");
346    /// ```
347    /// ## Program + Year
348    /// ```
349    /// use rumtk_core::rumtk_print_license_notice;
350    ///
351    /// rumtk_print_license_notice!("RUMTK", "2025");
352    /// ```
353    /// ## Program + Year + Authors
354    /// ```
355    /// use rumtk_core::rumtk_print_license_notice;
356    ///
357    /// rumtk_print_license_notice!("RUMTK", "2025", &vec!["Luis M. Santos, M.D."]);
358    /// ```
359    ///
360    #[macro_export]
361    macro_rules! rumtk_print_license_notice {
362        ( ) => {{
363            use $crate::cli::cli_utils::print_license_notice;
364
365            print_license_notice("RUMTK", "2025", &vec!["Luis M. Santos, M.D."]);
366        }};
367        ( $program:expr ) => {{
368            use $crate::cli::cli_utils::print_license_notice;
369            print_license_notice(&$program, "2025", &vec!["2025", "Luis M. Santos, M.D."]);
370        }};
371        ( $program:expr, $year:expr ) => {{
372            use $crate::cli::cli_utils::print_license_notice;
373            print_license_notice(&$program, &$year, &vec!["Luis M. Santos, M.D."]);
374        }};
375        ( $program:expr, $year:expr, $authors:expr ) => {{
376            use $crate::cli::cli_utils::print_license_notice;
377            print_license_notice(&$program, &$year, &$authors);
378        }};
379    }
380}