pub mod cli_utils {
use crate::core::{RUMResult, RUMVec};
use crate::strings::{rumtk_format, RUMStringConversions};
use crate::types::RUMBuffer;
use compact_str::CompactStringExt;
use std::io::{stdin, stdout, Read, Write};
pub const BUFFER_SIZE: usize = 1024 * 4;
pub const BUFFER_CHUNK_SIZE: usize = 512;
pub type BufferSlice = Vec<u8>;
pub type BufferChunk = [u8; BUFFER_CHUNK_SIZE];
pub fn read_stdin() -> RUMResult<RUMBuffer> {
let mut stdin_buffer = RUMVec::with_capacity(BUFFER_SIZE);
let mut s = read_some_stdin(&mut stdin_buffer)?;
while s > 0 {
s = read_some_stdin(&mut stdin_buffer)?;
if s < BUFFER_CHUNK_SIZE {
break;
}
}
Ok(RUMBuffer::from(stdin_buffer))
}
pub fn read_some_stdin(buf: &mut BufferSlice) -> RUMResult<usize> {
let mut chunk: BufferChunk = [0; BUFFER_CHUNK_SIZE];
match stdin().read(&mut chunk) {
Ok(s) => {
let slice = &chunk[0..s];
if s > 0 {
buf.extend_from_slice(slice);
}
Ok(s)
}
Err(e) => Err(rumtk_format!("Error reading stdin chunk because {}!", e)),
}
}
pub fn write_string_stdout(data: &str) -> RUMResult<()> {
write_stdout(&data.to_buffer())
}
pub fn write_stdout(data: &RUMBuffer) -> RUMResult<()> {
match stdout().write_all(data) {
Ok(_) => {}
Err(e) => return Err(rumtk_format!("Error writing to stdout because => {}", e)),
};
flush_stdout()?;
Ok(())
}
fn flush_stdout() -> RUMResult<()> {
match stdout().flush() {
Ok(_) => Ok(()),
Err(e) => Err(rumtk_format!("Error flushing stdout because => {}", e)),
}
}
pub fn print_license_notice(program: &str, year: &str, author_list: &Vec<&str>) {
let authors = author_list.join_compact(", ");
let notice = rumtk_format!(
r" {program} Copyright (C) {year} {authors}
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions."
);
eprintln!("{}", notice);
}
}
pub mod macros {
#[macro_export]
macro_rules! rumtk_read_stdin {
( ) => {{
use $crate::cli::cli_utils::read_stdin;
read_stdin()
}};
}
#[macro_export]
macro_rules! rumtk_write_stdout {
( $message:expr ) => {{
use $crate::cli::cli_utils::write_string_stdout;
write_string_stdout(&$message)
}};
( $message:expr, $binary:expr ) => {{
use $crate::cli::cli_utils::write_stdout;
write_stdout(&$message)
}};
}
#[macro_export]
macro_rules! rumtk_print_license_notice {
( ) => {{
use $crate::cli::cli_utils::print_license_notice;
print_license_notice("RUMTK", "2025", &vec!["Luis M. Santos, M.D."]);
}};
( $program:expr ) => {{
use $crate::cli::cli_utils::print_license_notice;
print_license_notice(&$program, "2025", &vec!["2025", "Luis M. Santos, M.D."]);
}};
( $program:expr, $year:expr ) => {{
use $crate::cli::cli_utils::print_license_notice;
print_license_notice(&$program, &$year, &vec!["Luis M. Santos, M.D."]);
}};
( $program:expr, $year:expr, $authors:expr ) => {{
use $crate::cli::cli_utils::print_license_notice;
print_license_notice(&$program, &$year, &$authors);
}};
}
}