pub mod cli_utils {
use crate::base::{RUMResult, RUMVec};
use crate::cpu::CPU_PAGE_SIZE;
use crate::strings::{rumtk_format, RUMString};
use crate::types::RUMCLIParser;
use rumtk_arena::AsRUMSlice;
use std::io::{stdin, stdout, BufWriter, Read, Write};
#[cfg(any(target_family = "unix", target_os = "linux", target_os = "macos"))]
use std::os::fd::{AsRawFd, FromRawFd};
pub type BufferSlice = RUMVec<u8>;
pub type CliSTDInput = RUMVec<u8>;
pub type CliSTDOutput<R: AsRUMSlice> = R;
pub type BufferChunk = [u8; STD_IN_STEP_SIZE];
const STD_IN_STEP_SIZE: usize = u16::MAX as usize;
pub enum CliProcessor<Args> {
Direct(fn(args: &Args) -> RUMResult<()>),
Message(fn(msg: RUMVec<u8>, args: &Args) -> RUMResult<RUMString>),
}
pub fn read_stdin(minimum_size: usize) -> RUMResult<CliSTDInput> {
let mut stdin_buffer = CliSTDInput::with_capacity(minimum_size);
loop {
let s = read_some_stdin(&mut stdin_buffer)?;
if s == 0 {
break;
}
}
Ok(stdin_buffer)
}
#[inline]
pub fn read_some_stdin(buf: &mut BufferSlice) -> RUMResult<usize> {
let mut chunk: BufferChunk = [0; STD_IN_STEP_SIZE];
match stdin().read(&mut chunk[..]) {
Ok(s) => {
buf.extend_from_slice(&chunk[..s]);
Ok(s)
}
Err(e) => Err(rumtk_format!("Error reading stdin chunk because {}!", e)),
}
}
#[cfg(target_os = "windows")]
pub fn write_stdout<R: AsSlice>(data: CliSTDOutput<R>) -> RUMResult<()> {
match stdout().write_all(data.as_rum_slice()) {
Ok(_) => {}
Err(e) => return Err(rumtk_format!("Error writing to stdout because => {}", e)),
};
flush_stdout()?;
Ok(())
}
#[cfg(any(target_family = "unix", target_os = "linux", target_os = "macos"))]
pub fn write_stdout<R: AsRUMSlice>(data: CliSTDOutput<R>) -> RUMResult<()> {
let stdout_fd = stdout().as_raw_fd();
{
let mut file = BufWriter::new(unsafe { std::fs::File::from_raw_fd(stdout_fd) });
match file.write_all(data.as_rum_slice()) {
Ok(_) => {
file.flush().unwrap_or_default();
std::mem::forget(file);
},
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 process_message<Args, PF, R>(args: &Args, processor: PF) -> RUMResult<()>
where
Args: RUMCLIParser,
R: AsRUMSlice,
PF: Fn(CliSTDInput, &Args) -> RUMResult<R>
{
let stdin_msg = read_stdin(CPU_PAGE_SIZE * CPU_PAGE_SIZE)?;
if !stdin_msg.is_empty() {
let out_data = processor(stdin_msg, args)?;
write_stdout(out_data)?;
}
Ok(())
}
pub fn process_message_loop<Args, PF>(args: &Args, processor: &PF)
where
Args: RUMCLIParser,
PF: Fn(CliSTDInput, &Args) -> RUMResult<RUMString>
{
loop {
match process_message(args, processor) {
Ok(()) => continue,
Err(e) => println!("{}", e), };
}
}
pub fn print_license_notice(program: &str, year: &str, author_list: &Vec<&str>) {
let authors = author_list.join(", ");
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_cli_define_args {
(
$(
$(#[$field_meta:meta])*
$field_name:ident : $field_typ:ty
),* $(,)?
) => {
#[derive($crate::types::RUMCLIParser, Debug)]
#[command(author, version, about, long_about = None)]
pub struct RUMTKInterfaceArgs {
$(
$(#[$field_meta])*
pub $field_name: $field_typ,
)*
#[arg(short, long, default_value_t = 1)]
pub threads: usize,
#[arg(short, long)]
pub quiet: bool,
#[arg(short, long)]
pub daemon: bool,
}
};
}
#[macro_export]
macro_rules! rumtk_read_stdin {
( ) => {{
use $crate::cpu::CPU_PAGE_SIZE;
use $crate::cli::cli_utils::{read_stdin};
read_stdin(CPU_PAGE_SIZE * CPU_PAGE_SIZE)
}};
( $min_expected_size:expr ) => {{
use $crate::cli::cli_utils::{read_stdin};
read_stdin($min_expected_size)
}};
}
#[macro_export]
macro_rules! rumtk_write_stdout {
( $message: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);
}};
}
#[macro_export]
macro_rules! rumtk_cli_process {
(
@collect [$($cli_args:tt)*]
$(#[$field_meta:meta])+
$field_name:ident : $field_typ:ty,
$($rest:tt)*
) => {
$crate::rumtk_cli_process!(
@collect [$($cli_args)* $(#[$field_meta])* $field_name : $field_typ,]
$($rest)*
)
};
(
@collect [$($cli_args:tt)*]
$field_name:ident : $field_typ:ty,
$($rest:tt)*
) => {
$crate::rumtk_cli_process!(
@collect [$($cli_args)* $field_name : $field_typ,]
$($rest)*
)
};
(
@collect [$($cli_args:tt)*]
$logic:expr $(,)?
) => {{
use $crate::cli::cli_utils::{process_message_loop, process_message, CliProcessor};
use $crate::types::RUMCLIParser;
$crate::rumtk_cli_define_args!($($cli_args)*);
let args = RUMTKInterfaceArgs::parse();
let r = match $logic {
CliProcessor::Direct(executor) => {
executor(&args)
},
CliProcessor::Message(executor) => {
if args.daemon {
Ok(process_message_loop(&args, &executor))
} else {
process_message(&args, &executor)
}
}
};
match r {
Ok(_) => {},
Err(e) => println!("Error: {}", e),
};
}};
(
$($tokens:tt)*
) => {
$crate::rumtk_cli_process!(@collect [] $($tokens)*)
};
}
}