rumtk-core 0.19.0

Core library for providing general functionality to support the other RUMTK crates. See rumtk-hl7-v2 crate as example
Documentation
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
/*
 * rumtk attempts to implement HL7 and medical protocols for interoperability in medicine.
 * This toolkit aims to be reliable, simple, performant, and standards compliant.
 * Copyright (C) 2025  Luis M. Santos, M.D. <lsantos@medicalmasses.com>
 * Copyright (C) 2025  MedicalMasses L.L.C. <contact@medicalmasses.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

///
/// Tools for handling reading and writing from the standard I/O/E.
///
/// Per this [stackoverflow discussion](https://unix.stackexchange.com/questions/37508/in-what-order-do-piped-commands-run).
/// Note:
///```text
///  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.
///
///  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
///
///  grep pattern very-large-file | tr a-z A-Z
///  begins to display the matching lines in uppercase even before grep has finished traversing the large file.
///
///  grep pattern very-large-file | head -n 1
///  displays the first matching line, and may stop processing well before grep has finished reading its input file.
///
///  If you read somewhere that piped programs run in sequence, flee this document. Piped programs run concurrently and always have.
/// ```
///
/// I bring the note above because that was my original understanding, but I have had to spend a
/// crazy amount of time trying to get data flowing from one process to another without the initial
/// process first exiting.
///
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, BufReader, 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];
    pub type CliDirectExecutor<Args: RUMCLIParser> = Box<dyn Fn(Args) -> RUMResult<()>>;
    pub type CliMessageExecutor<Args: RUMCLIParser, R: AsRUMSlice> = Box<dyn Fn(CliSTDInput, &Args) -> RUMResult<CliSTDOutput<R>>>;

    const STD_IN_STEP_SIZE: usize = u16::MAX as usize * 4;

    pub enum CliProcessor<Args>
    where
        Args: RUMCLIParser
    {
        Direct(CliDirectExecutor<Args>),
        Message(CliMessageExecutor<Args, RUMString>),

    }

    ///
    /// Consumes the incoming buffer in chunks of [CPU_PAGE_SIZE](CPU_PAGE_SIZE) bytes size
    /// until no more bytes are present.
    ///
    /// To avoid calling a blocking read, we check if the read yielded an amount of bytes fewer than
    /// the requested chunk size.
    ///
    /// ## Example
    ///
    /// ```
    /// use rumtk_core::cli::cli_utils::{read_stdin};
    /// use rumtk_core::cpu::CPU_PAGE_SIZE;
    ///
    /// let stdin_data = read_stdin(CPU_PAGE_SIZE).unwrap();
    ///
    /// assert_eq!(stdin_data.len(), 0, "Returned data with {} size even though we expected 0 bytes!", stdin_data.len())
    /// ```
    ///
    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 we attempt the next read, it is likely to be a 0 byte read. Why does this matter?
            // Well, if the other end of the pipe is still open, the read call will stall in Rust's
            // std and it is because it expects EOF but that never comes.
            // If you look at https://man7.org/linux/man-pages/man2/read.2.html, read should return
            // 0 and simply let us naturally break, but a read < than requested buffer appears to be
            // an equally valid way to handle terminal and piped data.
            // We have to check against 0 because the more optimal the buffer size we ask for (e.g.
            // larger reads for minimum syscall time) the less likely the kernel is ready with the
            // requested data.

            // Example reads at u16::Max
            // Read 65535 bytes
            // Read 61441 bytes
            // Read 65535 bytes
            // Read 61441 bytes
            // Read 8192 bytes
            // Read 65535 bytes
            // Read 61441 bytes
            // Read 65535 bytes
            // Read 61441 bytes
            // Read 8192 bytes
            // Read 65535 bytes
            // Read 61441 bytes
            // Read 65535 bytes
            // Read 61441 bytes
            // Read 8192 bytes
            // Read 65535 bytes
            // Read 61441 bytes
            // Read 65535 bytes
            // Read 61441 bytes
            // Read 8192 bytes
            // Read 65535 bytes
            // Read 61441 bytes
            // Read 65535 bytes
            // Read 61441 bytes
            // Read 8192 bytes
            // Read 65535 bytes
            // Read 61441 bytes
            // Read 65535 bytes
            // Read 61441 bytes
            // Read 8192 bytes
            // Read 65535 bytes
            // Read 61441 bytes
            // Read 65535 bytes
            // Read 61441 bytes
            // Read 8192 bytes
            // Read 65535 bytes
            // Read 61441 bytes
            // Read 65535 bytes
            // Read 61441 bytes
            // Read 8192 bytes
            // Read 65535 bytes
            // Read 61441 bytes
            // Read 65535 bytes
            // Read 41974 bytes
            // Read 0 bytes
            // Total: 2331637 => 2.2MB
            if s == 0 {
                break;
            }
        }

        Ok(stdin_buffer)
    }

    ///
    /// Consumes the incoming buffer in chunks of [CPU_SIMD_64_SIZE](crate::cpu::CPU_SIMD_64_SIZE) bytes size.
    ///
    /// ## Example
    ///
    /// ```
    /// use std::io::stdin;
    /// use std::io::prelude::*;
    /// use std::process::{Command, Stdio};
    /// use rumtk_core::cli::cli_utils::{read_some_stdin};
    /// use rumtk_core::cpu::CPU_PAGE_SIZE;
    /// use rumtk_core::base::RUMVec;
    ///
    /// let mut stdin_buffer = RUMVec::with_capacity(CPU_PAGE_SIZE);
    /// let mut s = read_some_stdin(&mut stdin_buffer).unwrap();
    /// let mut totas_s = s;
    /// while s > 0 {
    ///    s = read_some_stdin(&mut stdin_buffer).unwrap();
    ///    totas_s += s;
    /// }
    ///
    /// assert_eq!(totas_s, 0, "Returned data with {} size even though we expected 0 bytes!", totas_s)
    /// ```
    ///
    #[inline]
    #[cfg(target_os = "windows")]
    pub fn read_some_stdin(buf: &mut BufferSlice) -> RUMResult<usize> {
        let mut chunk: BufferChunk = [0; STD_IN_STEP_SIZE];

        match stdin().lock().read(&mut chunk[..]) {
            Ok(s) => {
                buf.extend_from_slice(&chunk[..s]);
                Ok(s)
            }
            Err(e) => Err(rumtk_format!("Error reading stdin chunk because {}!", e)),
        }
    }

    ///
    /// Consumes the incoming buffer in chunks of [CPU_SIMD_64_SIZE](crate::cpu::CPU_SIMD_64_SIZE) bytes size.
    ///
    /// ## Example
    ///
    /// ```
    /// use std::io::stdin;
    /// use std::io::prelude::*;
    /// use std::process::{Command, Stdio};
    /// use rumtk_core::cli::cli_utils::{read_some_stdin};
    /// use rumtk_core::cpu::CPU_PAGE_SIZE;
    /// use rumtk_core::base::RUMVec;
    ///
    /// let mut stdin_buffer = RUMVec::with_capacity(CPU_PAGE_SIZE);
    /// let mut s = read_some_stdin(&mut stdin_buffer).unwrap();
    /// let mut totas_s = s;
    /// while s > 0 {
    ///    s = read_some_stdin(&mut stdin_buffer).unwrap();
    ///    totas_s += s;
    /// }
    ///
    /// assert_eq!(totas_s, 0, "Returned data with {} size even though we expected 0 bytes!", totas_s)
    /// ```
    ///
    #[cfg(any(target_family = "unix", target_os = "linux", target_os = "macos"))]
    pub fn read_some_stdin(buf: &mut BufferSlice) -> RUMResult<usize> {
        // Create an unbuffered File handle from file descriptor 1 (stdout)
        let locked = stdin().lock();
        let stdin_fd = locked.as_raw_fd();
        let mut chunk: BufferChunk = [0; STD_IN_STEP_SIZE];

        let mut file = BufReader::new(unsafe { std::fs::File::from_raw_fd(stdin_fd) });

        //Read directly from std input
        let count = match file.read(&mut chunk[..]) {
            Ok(s) => {
                buf.extend_from_slice(&chunk[..s]);
                std::mem::forget(file);
                s
            },
            Err(e) => return Err(rumtk_format!("Error writing to stdout because {}", e)),
        };

        Ok(count)
    }

    ///
    /// Writes [RUMBuffer] to `stdout`.
    ///
    #[cfg(target_os = "windows")]
    pub fn write_stdout<R: AsSlice>(data: CliSTDOutput<R>) -> RUMResult<()> {
        match stdout().lock().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<()> {
        // Create an unbuffered File handle from file descriptor 1 (stdout)
        let locked = stdout().lock();
        let stdout_fd = locked.as_raw_fd();
        println!("stdin_fd: {}", stdout_fd);

        let mut file = BufWriter::new(unsafe { std::fs::File::from_raw_fd(stdout_fd) });

        // Write bytes directly
        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(())
    }

    ///
    /// Runs a closure (or any `Fn`) that owns the whole lifecycle of the program. Unlike
    /// [CliProcessor::Direct], the closure is not boxed, so it can borrow from its environment.
    ///
    pub fn run_direct<Args, F>(args: &Args, logic: F) -> RUMResult<()>
    where
        Args: RUMCLIParser,
        F: Fn(&Args) -> RUMResult<()>
    {
        logic(args)
    }

    pub fn process_message_loop<Args, PF, R>(args: Args, processor: &PF)
    where
        Args: RUMCLIParser,
        R: AsRUMSlice,
        PF: Fn(CliSTDInput, &Args) -> RUMResult<R>
    {
        loop {
            match process_message(&args, processor) {
                Ok(()) => continue,
                Err(e) => println!("{}", e), // TODO: missing log call
            };
        }
    }

    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,
                )*
                ///
                /// Specifies command line script to execute on message.
                ///
                #[arg(short, long, default_value_t = 1)]
                pub threads: usize,
                ///
                /// Don't write to stdout. Mostly used to distinguish between performance issues with parser
                /// vs. serde's JSON serialization.
                ///
                #[arg(short, long)]
                pub quiet: bool,
                ///
                /// Only used if in client/outbound mode. Places the interface into a loop constantly looking
                /// for messages in stdin to ship to the connected listening interface.
                ///
                #[arg(short, long)]
                pub daemon: bool,
            }
        };
    }

    ///
    /// Reads STDIN and unescapes the incoming message.
    /// Return this unescaped message.
    ///
    /// # Example
    ///
    /// ## Without specifying the minimum read size.
    /// ```
    /// use rumtk_core::base::{RUMResult, RUMVec};
    /// use rumtk_core::buffers::*;
    /// use rumtk_core::rumtk_read_stdin;
    ///
    /// fn test_read_stdin() -> RUMResult<RUMVec<u8>> {
    ///     rumtk_read_stdin!()
    /// }
    ///
    /// match test_read_stdin() {
    ///     Ok(s) => (),
    ///     Err(e) => panic!("Error reading stdin because => {}", e)
    /// }
    /// ```
    ///
    /// ## With specifying the minimum read size.
    /// ```
    /// use rumtk_core::base::{RUMResult, RUMVec};
    /// use rumtk_core::buffers::*;
    /// use rumtk_core::rumtk_read_stdin;
    ///
    /// fn test_read_stdin() -> RUMResult<RUMVec<u8>> {
    ///     rumtk_read_stdin!(1024)
    /// }
    ///
    /// match test_read_stdin() {
    ///     Ok(s) => (),
    ///     Err(e) => panic!("Error reading stdin because => {}", e)
    /// }
    /// ```
    ///
    #[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)
        }};
    }

    ///
    /// Writes [RUMString](crate::strings::RUMString) or [RUMBuffer](crate::types::RUMBuffer) to `stdout`.
    ///
    /// If the `binary` parameter is passed, we push the `message` parameter directly to `stdout`. the
    /// `message` parameter has to be of type [RUMBuffer](crate::types::RUMBuffer).
    ///
    /// ## Example
    ///
    /// ### Default / Pushing a String
    /// ```
    /// use rumtk_core::rumtk_write_stdout;
    ///
    /// rumtk_write_stdout!("I ❤ my wife!");
    /// ```
    ///
    /// ## Pushing Binary Buffer
    /// ```
    /// use rumtk_core::rumtk_write_stdout;
    /// use rumtk_core::buffers::{new_random_rumbuffer, DEFAULT_BUFFER_CHUNK_SIZE};
    ///
    /// let buffer = new_random_rumbuffer::<DEFAULT_BUFFER_CHUNK_SIZE>();
    /// rumtk_write_stdout!(buffer);
    /// ```
    ///
    #[macro_export]
    macro_rules! rumtk_write_stdout {
        ( $message:expr ) => {{
            use $crate::cli::cli_utils::write_stdout;
            write_stdout(&$message)
        }};
    }

    ///
    /// Prints the mandatory GPL License Notice to terminal!
    ///
    /// # Example
    /// ## Default
    /// ```
    /// use rumtk_core::rumtk_print_license_notice;
    ///
    /// rumtk_print_license_notice!();
    /// ```
    /// ## Program Only
    /// ```
    /// use rumtk_core::rumtk_print_license_notice;
    ///
    /// rumtk_print_license_notice!("RUMTK");
    /// ```
    /// ## Program + Year
    /// ```
    /// use rumtk_core::rumtk_print_license_notice;
    ///
    /// rumtk_print_license_notice!("RUMTK", "2025");
    /// ```
    /// ## Program + Year + Authors
    /// ```
    /// use rumtk_core::rumtk_print_license_notice;
    ///
    /// rumtk_print_license_notice!("RUMTK", "2025", &vec!["Luis M. Santos, M.D."]);
    /// ```
    ///
    #[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);
        }};
    }

    ///
    /// Defines the CLI arguments of the program, parses the command line, and wires the message
    /// processing logic.
    ///
    /// The macro expects an optional list of CLI argument definitions (same syntax accepted by
    /// [rumtk_cli_define_args](crate::rumtk_cli_define_args)) followed by either the two message
    /// handlers:
    ///
    /// + `ok`  => Called when the incoming message could be deserialized into the expected type.
    /// + `err` => Called with the raw bytes when deserialization was not possible.
    ///
    /// or a single piece of logic receiving the parsed arguments. In the latter case, the logic
    /// owns the whole interface lifecycle and is called once with a reference to the parsed
    /// arguments.
    ///
    /// The generated argument struct is named `RUMTKInterfaceArgs` and is available to the
    /// handlers. If the `--daemon` flag is passed, the `ok`/`err` handlers are called in a loop for
    /// every message coming through `stdin`. Otherwise, a single message is processed.
    ///
    /// ## Example
    ///
    /// ### Example 1 - With Parsed and Unparsed Message Closures
    /// 
    /// ```no_run
    /// use rumtk_core::base::{RUMResult, RUMVec};
    /// use rumtk_core::strings::RUMString;
    /// use rumtk_core::types::RUMCLIParser;
    /// use rumtk_core::rumtk_cli_process;
    ///
    /// fn main() {
    ///     rumtk_cli_process!(
    ///         ///
    ///         /// Pretty print the outgoing message.
    ///         ///
    ///         #[arg(short, long)]
    ///         pretty: bool,
    ///         ///
    ///         /// Run in debug mode?
    ///         ///
    ///         #[arg(short, long)]
    ///         debug: bool,
    ///         Message(|data: RUMVec<u8>, args: &RUMTKInterfaceArgs| -> RUMResult<RUMString> {
    ///             Ok(RUMString::default())
    ///         })
    ///     );
    /// }
    /// ```
    ///
    /// ### Example 2 - With Raw Logic
    ///
    /// ```no_run
    /// use rumtk_core::base::{RUMResult, RUMVec};
    /// use rumtk_core::strings::RUMString;
    /// use rumtk_core::types::RUMCLIParser;
    /// use rumtk_core::rumtk_cli_process;
    ///
    /// fn main() {
    ///     rumtk_cli_process!(
    ///         ///
    ///         /// Pretty print the outgoing message.
    ///         ///
    ///         #[arg(short, long)]
    ///         pretty: bool,
    ///         ///
    ///         /// Run in debug mode?
    ///         ///
    ///         #[arg(short, long)]
    ///         debug: bool,
    ///         Direct(|args: &RUMTKInterfaceArgs| -> RUMResult<()> {
    ///             Ok(())
    ///         })
    ///     );
    /// }
    /// ```
    ///
    /// ## Notes
    ///
    /// I let `Claude Opus 5` help complete this macro. I did not understand how to wire the
    /// token tree muncher into the argument pattern to pass to [rumtk_cli_define_args](crate::rumtk_cli_define_args)
    /// and the two additional arguments representing the closures to be executed if message parsing is successful or not.
    ///
    #[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)*]
            Direct($logic:expr) $(,)?
        ) => {{
            use $crate::cli::cli_utils::run_direct;
            use $crate::types::RUMCLIParser;

            $crate::rumtk_cli_define_args!($($cli_args)*);

            let args = RUMTKInterfaceArgs::parse();

            match run_direct(&args, $logic) {
                Ok(_) => {},
                Err(e) => println!("Error: {}", e),
            };
        }};
        (
            @collect [$($cli_args:tt)*]
            Message($logic:expr) $(,)?
        ) => {{
            use $crate::cli::cli_utils::{process_message_loop, process_message};
            use $crate::types::RUMCLIParser;

            $crate::rumtk_cli_define_args!($($cli_args)*);

            let args = RUMTKInterfaceArgs::parse();
            let processor = $logic;

            let r = if args.daemon {
                process_message_loop(args, &processor);
                Ok(())
            } else {
                process_message(&args, &processor)
            };

            match r {
                Ok(_) => {},
                Err(e) => println!("Error: {}", e),
            };
        }};
        (
            $($tokens:tt)*
        ) => {
            $crate::rumtk_cli_process!(@collect [] $($tokens)*)
        };
    }
}