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::core::{RUMResult, RUMVec};
46    use crate::strings::{rumtk_format, RUMStringConversions};
47    use crate::types::RUMBuffer;
48    use compact_str::CompactStringExt;
49    use std::io::{stdin, stdout, Read, Write};
50
51    pub const BUFFER_SIZE: usize = 1024 * 4;
52    pub const BUFFER_CHUNK_SIZE: usize = 512;
53
54    pub type BufferSlice = Vec<u8>;
55    pub type BufferChunk = [u8; BUFFER_CHUNK_SIZE];
56
57    ///
58    /// Consumes the incoming buffer in chunks of [BUFFER_CHUNK_SIZE](BUFFER_CHUNK_SIZE) bytes size
59    /// until no more bytes are present.
60    ///
61    /// To avoid calling a blocking read, we check if the read yielded an amount of bytes fewer than
62    /// the requested chunk size.
63    ///
64    /// ## Example
65    ///
66    /// ```
67    /// use rumtk_core::cli::cli_utils::{read_stdin};
68    ///
69    /// let stdin_data = read_stdin().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() -> RUMResult<RUMBuffer> {
75        let mut stdin_buffer = RUMVec::with_capacity(BUFFER_SIZE);
76        let mut s = read_some_stdin(&mut stdin_buffer)?;
77
78        while s > 0 {
79            s = read_some_stdin(&mut stdin_buffer)?;
80
81            // If we attempt the next read, it is likely to be a 0 byte read. Why does this matter?
82            // Well, if the other end of the pipe is still open, the read call will stall in Rust's
83            // std and I am not sure why.
84            // If you look at https://man7.org/linux/man-pages/man2/read.2.html, read should return
85            // 0 and simply let us naturally break, but a read < than requested buffer appears to be
86            // an equally canonical way to handle terminal and piped data.
87            if s < BUFFER_CHUNK_SIZE {
88                break;
89            }
90        }
91
92        Ok(RUMBuffer::from(stdin_buffer))
93    }
94
95    ///
96    /// Consumes the incoming buffer in chunks of [BUFFER_CHUNK_SIZE](BUFFER_CHUNK_SIZE) bytes size.
97    ///
98    /// ## Example
99    ///
100    /// ```
101    /// use std::io::stdin;
102    /// use std::io::prelude::*;
103    /// use std::process::{Command, Stdio};
104    /// use rumtk_core::cli::cli_utils::{read_some_stdin, BUFFER_SIZE, BUFFER_CHUNK_SIZE};
105    /// use rumtk_core::core::RUMVec;
106    ///
107    /// let mut stdin_buffer = RUMVec::with_capacity(BUFFER_SIZE);
108    /// let mut s = read_some_stdin(&mut stdin_buffer).unwrap();
109    /// let mut totas_s = s;
110    /// while s > 0 {
111    ///    s = read_some_stdin(&mut stdin_buffer).unwrap();
112    ///    totas_s += s;
113    /// }
114    ///
115    /// assert_eq!(totas_s, 0, "Returned data with {} size even though we expected 0 bytes!", totas_s)
116    /// ```
117    ///
118    pub fn read_some_stdin(buf: &mut BufferSlice) -> RUMResult<usize> {
119        let mut chunk: BufferChunk = [0; BUFFER_CHUNK_SIZE];
120        match stdin().read(&mut chunk) {
121            Ok(s) => {
122                let slice = &chunk[0..s];
123
124                if s > 0 {
125                    buf.extend_from_slice(slice);
126                }
127
128                Ok(s)
129            }
130            Err(e) => Err(rumtk_format!("Error reading stdin chunk because {}!", e)),
131        }
132    }
133
134    ///
135    /// writes [`stringview`] to `stdout`.
136    ///
137    pub fn write_string_stdout(data: &str) -> RUMResult<()> {
138        write_stdout(&data.to_buffer())
139    }
140
141    ///
142    /// Writes [RUMBuffer] to `stdout`.
143    ///
144    pub fn write_stdout(data: &RUMBuffer) -> RUMResult<()> {
145        match stdout().write_all(data) {
146            Ok(_) => {}
147            Err(e) => return Err(rumtk_format!("Error writing to stdout because => {}", e)),
148        };
149        flush_stdout()?;
150        Ok(())
151    }
152
153    fn flush_stdout() -> RUMResult<()> {
154        match stdout().flush() {
155            Ok(_) => Ok(()),
156            Err(e) => Err(rumtk_format!("Error flushing stdout because => {}", e)),
157        }
158    }
159
160    pub fn print_license_notice(program: &str, year: &str, author_list: &Vec<&str>) {
161        let authors = author_list.join_compact(", ");
162        let notice = rumtk_format!(
163            r"  {program}  Copyright (C) {year}  {authors}
164                This program comes with ABSOLUTELY NO WARRANTY.
165                This is free software, and you are welcome to redistribute it
166                under certain conditions."
167        );
168        eprintln!("{}", notice);
169    }
170}
171
172pub mod macros {
173    ///
174    /// Reads STDIN and unescapes the incoming message.
175    /// Return this unescaped message.
176    ///
177    /// # Example
178    /// ```
179    /// use rumtk_core::core::RUMResult;
180    /// use rumtk_core::types::RUMBuffer;
181    /// use rumtk_core::rumtk_read_stdin;
182    ///
183    /// fn test_read_stdin() -> RUMResult<RUMBuffer> {
184    ///     rumtk_read_stdin!()
185    /// }
186    ///
187    /// match test_read_stdin() {
188    ///     Ok(s) => (),
189    ///     Err(e) => panic!("Error reading stdin because => {}", e)
190    /// }
191    /// ```
192    ///
193    #[macro_export]
194    macro_rules! rumtk_read_stdin {
195        (  ) => {{
196            use $crate::cli::cli_utils::read_stdin;
197            read_stdin()
198        }};
199    }
200
201    ///
202    /// Writes [RUMString](crate::strings::RUMString) or [RUMBuffer](crate::types::RUMBuffer) to `stdout`.
203    ///
204    /// If the `binary` parameter is passed, we push the `message` parameter directly to `stdout`. the
205    /// `message` parameter has to be of type [RUMBuffer](crate::types::RUMBuffer).
206    ///
207    /// ## Example
208    ///
209    /// ### Default / Pushing a String
210    /// ```
211    /// use rumtk_core::rumtk_write_stdout;
212    ///
213    /// rumtk_write_stdout!("I ❤ my wife!");
214    /// ```
215    ///
216    /// ## Pushing Binary Buffer
217    /// ```
218    /// use rumtk_core::rumtk_write_stdout;
219    /// use rumtk_core::core::new_random_buffer;
220    ///
221    /// let buffer = new_random_buffer();
222    /// rumtk_write_stdout!(buffer, true);
223    /// ```
224    ///
225    #[macro_export]
226    macro_rules! rumtk_write_stdout {
227        ( $message:expr ) => {{
228            use $crate::cli::cli_utils::write_string_stdout;
229            write_string_stdout(&$message)
230        }};
231        ( $message:expr, $binary:expr ) => {{
232            use $crate::cli::cli_utils::write_stdout;
233            write_stdout(&$message)
234        }};
235    }
236
237    ///
238    /// Prints the mandatory GPL License Notice to terminal!
239    ///
240    /// # Example
241    /// ## Default
242    /// ```
243    /// use rumtk_core::rumtk_print_license_notice;
244    ///
245    /// rumtk_print_license_notice!();
246    /// ```
247    /// ## Program Only
248    /// ```
249    /// use rumtk_core::rumtk_print_license_notice;
250    ///
251    /// rumtk_print_license_notice!("RUMTK");
252    /// ```
253    /// ## Program + Year
254    /// ```
255    /// use rumtk_core::rumtk_print_license_notice;
256    ///
257    /// rumtk_print_license_notice!("RUMTK", "2025");
258    /// ```
259    /// ## Program + Year + Authors
260    /// ```
261    /// use rumtk_core::rumtk_print_license_notice;
262    ///
263    /// rumtk_print_license_notice!("RUMTK", "2025", &vec!["Luis M. Santos, M.D."]);
264    /// ```
265    ///
266    #[macro_export]
267    macro_rules! rumtk_print_license_notice {
268        ( ) => {{
269            use $crate::cli::cli_utils::print_license_notice;
270
271            print_license_notice("RUMTK", "2025", &vec!["Luis M. Santos, M.D."]);
272        }};
273        ( $program:expr ) => {{
274            use $crate::cli::cli_utils::print_license_notice;
275            print_license_notice(&$program, "2025", &vec!["2025", "Luis M. Santos, M.D."]);
276        }};
277        ( $program:expr, $year:expr ) => {{
278            use $crate::cli::cli_utils::print_license_notice;
279            print_license_notice(&$program, &$year, &vec!["Luis M. Santos, M.D."]);
280        }};
281        ( $program:expr, $year:expr, $authors:expr ) => {{
282            use $crate::cli::cli_utils::print_license_notice;
283            print_license_notice(&$program, &$year, &$authors);
284        }};
285    }
286}