ctb_formats_math/
cli.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! CLI handlers for base conversion utilities.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29pub use crate as ctb_formats_math;
30use anyhow::{Result, anyhow};
31
32use crate::base::{
33    BaseAlphabet, BaseConversionPaddingMode, BaseStringFormatSettings,
34    base_to_base_string,
35};
36
37/// Alphabet selection for base conversions.
38#[derive(clap::ValueEnum, Debug, Clone, Copy, PartialEq, Eq, Default)]
39pub enum CliBaseAlphabet {
40    /// Standard alphanumeric alphabet (0-9, a-z), supporting bases up to 36.
41    #[default]
42    Standard,
43    /// Standard RFC 4648 Base64 alphabet (A-Z = 0..25, a-z = 26..51,
44    /// 0-9 = 52..61, + = 62, / = 63), supporting radix up to 64.
45    ///
46    /// NOTE: This is for mathematical positional place-value numerals (e.g. 64
47    /// is represented as "BA"), NOT RFC 4648 octet-stream data armoring (where
48    /// 0xFF encodes to "/w=="). For encoding binary files or raw byte streams,
49    /// use data armor tools like `hexdump`, `bin2hex`, or dedicated base64
50    /// commands.
51    #[value(
52        name = "base64_standard",
53        alias = "base64-standard",
54        alias = "base64"
55    )]
56    Base64Standard,
57}
58
59impl From<CliBaseAlphabet> for BaseAlphabet {
60    fn from(cli: CliBaseAlphabet) -> Self {
61        match cli {
62            CliBaseAlphabet::Standard => Self::Standard,
63            CliBaseAlphabet::Base64Standard => Self::Base64Standard,
64        }
65    }
66}
67
68impl CliBaseAlphabet {
69    #[must_use]
70    pub fn max_base(self) -> u8 {
71        BaseAlphabet::from(self).max_base()
72    }
73}
74
75#[derive(clap::Args, Debug, Clone, PartialEq, Eq)]
76#[expect(
77    clippy::struct_excessive_bools,
78    reason = "clap CLI options mapping structure"
79)]
80pub struct BaseArgs {
81    // ------------------------------------------------------------------------
82    // Padding & Chunking
83    // ------------------------------------------------------------------------
84    /// Shortcut for byte-sized conversion: chunks numbers into byte units
85    /// (`--limit 255 --pad`) and suppresses non-fatal warnings.
86    ///
87    /// Note: This is for chunking lists of numbers. To convert raw binary data
88    /// or files to/from hex streams, use `bin2hex` and `hex2bin`. See also
89    /// `hexdump`.
90    #[arg(
91        short,
92        long,
93        default_value_t = false,
94        help_heading = "Padding & Chunking"
95    )]
96    pub bytes: bool,
97
98    /// Disables zero-padding when using the `--bytes` shortcut.
99    #[arg(
100        long,
101        default_value_t = false,
102        requires = "bytes",
103        help_heading = "Padding & Chunking"
104    )]
105    pub no_pad: bool,
106
107    /// Limit maximum value for number chunking. Input numbers longer than the
108    /// digit width needed to represent this value will be split into chunks
109    /// (e.g. limit 255 splits continuous hex into 2-digit byte chunks).
110    /// Set to 0 to disable chunking.
111    #[arg(
112        short,
113        long,
114        default_value_t = 0,
115        help_heading = "Padding & Chunking"
116    )]
117    pub limit: u64,
118
119    /// Zero-pad the left of each number to the full digit width determined by
120    /// the `--limit` argument (e.g. 2 hex digits or 8 binary digits for 255).
121    /// Requires `--limit` to be set.
122    #[arg(
123        short,
124        long,
125        default_value_t = false,
126        conflicts_with("pad_l"),
127        requires_if("true", "limit"),
128        help_heading = "Padding & Chunking"
129    )]
130    pub pad: bool,
131
132    /// Left-pad each number with leading zeros to at least this many digits.
133    /// Set to 0 or 1 to disable fixed padding.
134    #[arg(
135        short = 'P',
136        long,
137        default_value_t = 1,
138        conflicts_with("pad"),
139        help_heading = "Padding & Chunking"
140    )]
141    pub pad_l: u32,
142
143    // ------------------------------------------------------------------------
144    // Formatting & Delimiters
145    // ------------------------------------------------------------------------
146    /// Prefix to prepend to each output number (e.g. "0x" for hexadecimal).
147    #[arg(long, default_value = "", help_heading = "Formatting & Delimiters")]
148    pub prefix: String,
149
150    /// Delimiter string inserted between separate output numbers.
151    #[arg(
152        short,
153        long,
154        default_value = " ",
155        help_heading = "Formatting & Delimiters"
156    )]
157    pub separator: String,
158
159    /// Output letter digits in bases > 10 using lowercase letters instead of
160    /// uppercase. Does not change case of non-digit characters.
161    #[arg(
162        long,
163        default_value_t = true,
164        help_heading = "Formatting & Delimiters"
165    )]
166    pub lowercase: bool,
167
168    // ------------------------------------------------------------------------
169    // Input Parsing & Filtering
170    // ------------------------------------------------------------------------
171    /// Recognize and strip standard radix prefixes (such as "0x", "0b", "0o")
172    /// from input numbers.
173    #[arg(
174        long,
175        default_value_t = true,
176        help_heading = "Input Parsing & Filtering"
177    )]
178    pub parse_prefixes: bool,
179
180    /// Filter out non-digit characters between numbers in the formatted output.
181    /// If false, non-digit punctuation is echoed literally.
182    #[arg(
183        short,
184        long,
185        default_value_t = true,
186        help_heading = "Input Parsing & Filtering"
187    )]
188    pub filter_chars: bool,
189
190    /// Ignore non-digit characters inline while parsing numbers, preventing
191    /// them from splitting numbers (e.g. "`10_000`" parses as 10000).
192    #[arg(
193        short,
194        long,
195        default_value_t = false,
196        help_heading = "Input Parsing & Filtering"
197    )]
198    pub collapse_filtered: bool,
199
200    /// Specific non-digit characters to collapse inline silently without
201    /// emitting warnings (e.g. `--collapse-only "_"`).
202    #[arg(
203        long,
204        default_value = "[]",
205        help_heading = "Input Parsing & Filtering"
206    )]
207    pub collapse_only: Vec<String>,
208
209    // ------------------------------------------------------------------------
210    // Numeral Systems & Alphabets
211    // ------------------------------------------------------------------------
212    /// Alphabet to use for parsing input numbers. Bases > 36 (up to 64) require
213    /// specifying an alphabet like `base64_standard`.
214    #[arg(
215        long,
216        value_enum,
217        default_value = "standard",
218        help_heading = "Numeral Systems & Alphabets"
219    )]
220    pub input_alphabet: CliBaseAlphabet,
221
222    /// Alphabet to use for formatting output numbers. Bases > 36 (up to 64)
223    /// require specifying an alphabet like `base64_standard`.
224    #[arg(
225        long,
226        value_enum,
227        default_value = "standard",
228        help_heading = "Numeral Systems & Alphabets"
229    )]
230    pub output_alphabet: CliBaseAlphabet,
231
232    // ------------------------------------------------------------------------
233    // Output Options
234    // ------------------------------------------------------------------------
235    /// Suppress non-fatal warning messages.
236    #[arg(
237        short,
238        long,
239        default_value_t = false,
240        help_heading = "Output Options"
241    )]
242    pub quiet: bool,
243}
244
245impl Default for BaseArgs {
246    fn default() -> Self {
247        Self {
248            bytes: false,
249            no_pad: false,
250            prefix: String::new(),
251            separator: " ".to_string(),
252            lowercase: true,
253            filter_chars: true,
254            collapse_filtered: false,
255            collapse_only: Vec::new(),
256            parse_prefixes: true,
257            limit: 0,
258            pad: false,
259            pad_l: 1,
260            input_alphabet: CliBaseAlphabet::Standard,
261            output_alphabet: CliBaseAlphabet::Standard,
262            quiet: false,
263        }
264    }
265}
266
267#[derive(clap::Args, Debug, Clone, PartialEq, Eq)]
268pub struct BaseToBaseArgs {
269    /// Base of input numbers
270    #[arg(default_value_t = 10)]
271    pub from_base: u8,
272
273    /// Base of output numbers
274    #[arg(default_value_t = 10)]
275    pub to_base: u8,
276}
277
278// ---------------------------
279// Conversion Logic
280// ---------------------------
281
282#[expect(
283    clippy::unnecessary_wraps,
284    reason = "uniform tool command execution interface"
285)]
286pub fn run_base_convert(
287    from_base: &Option<u8>,
288    to_base: &Option<u8>,
289    input: &str,
290    args: &BaseArgs,
291) -> Result<ToolResult> {
292    let mut format_settings = BaseStringFormatSettings {
293        prefix: args.prefix.clone(),
294        separator: args.separator.clone(),
295        lowercase: args.lowercase,
296        filter_chars: args.filter_chars,
297        collapse_filtered: args.collapse_filtered,
298        collapse_only: args.collapse_only.clone(),
299        parse_prefixes: args.parse_prefixes,
300        limit: args.limit,
301        pad: BaseConversionPaddingMode {
302            pad_l: args.pad_l,
303            pad_fit: args.pad,
304        },
305        input_alphabet: args.input_alphabet.into(),
306        output_alphabet: args.output_alphabet.into(),
307    };
308
309    if args.bytes {
310        format_settings.limit = u64::from(u8::MAX);
311        format_settings.pad = BaseConversionPaddingMode {
312            // I'm using 0 as the default here to indicate it's fully off, while
313            // the struct and the CLI argument default to 1 because logically,
314            // it makes sense to show each number as at least 1 byte wide. In
315            // practice, 0 and 1 have no effect.
316            pad_l: 0,
317            pad_fit: true,
318        };
319        if args.no_pad {
320            format_settings.pad = BaseConversionPaddingMode {
321                pad_l: 0,
322                pad_fit: false,
323            };
324        }
325    } else if args.no_pad {
326        return Ok(ToolResult::immediate_err(
327            "--no-pad is only valid with --bytes\n".as_bytes().to_vec(),
328            1,
329        ));
330    }
331
332    let quiet = args.quiet || args.bytes;
333
334    if (from_base.is_none() && !to_base.is_none())
335        || (!from_base.is_none() && to_base.is_none())
336    {
337        return Ok(ToolResult::immediate_err(
338            "Either both or neither base must be specified\n"
339                .as_bytes()
340                .to_vec(),
341            1,
342        ));
343    }
344
345    // Reason for fallback: base_to_base_string takes optional from_base and to_base CLI arguments. When both are None (neither explicitly supplied by user), the CLI command defaults to decimal (base 10) for both input and output.
346    let converted = base_to_base_string(
347        input,
348        from_base.unwrap_or(10),
349        to_base.unwrap_or(10),
350        &format_settings,
351    );
352
353    match converted {
354        Err(e) => Ok(ToolResult::immediate_err(
355            format!("{e:?}\n").as_bytes().to_vec(),
356            1,
357        )),
358        Ok((res, log)) => {
359            let mut output_bytes = res.into_bytes();
360            output_bytes.push(b'\n');
361            let stderr_bytes = if quiet {
362                log.format_errors().into_bytes()
363            } else {
364                log.format_all().into_bytes()
365            };
366            Ok(ToolResult::Immediate {
367                stdout: output_bytes,
368                stderr: stderr_bytes,
369                exit_code: 0,
370            })
371        }
372    }
373}
374
375/// Executes base2base CLI command logic.
376pub fn run_base2base(
377    args: &[String],
378    base_args: &BaseArgs,
379) -> Result<ToolResult> {
380    let input_max_base = base_args.input_alphabet.max_base();
381    let output_max_base = base_args.output_alphabet.max_base();
382
383    let (input, from_base, to_base) = if args.len() >= 3
384        && let (Ok(from), Ok(to)) = (
385            args.first()
386                .ok_or_else(|| anyhow!("Missing from_base"))?
387                .parse::<u8>(),
388            args.get(1)
389                .ok_or_else(|| anyhow!("Missing to_base"))?
390                .parse::<u8>(),
391        ) {
392        if !(1..=input_max_base).contains(&from) {
393            let err_msg = if from > 36 {
394                format!(
395                    "Base out of range (from: {from}). Bases > 36 (up to 64) require --input-alphabet base64_standard.\n"
396                )
397            } else {
398                format!(
399                    "Invalid base (from: {from}). Supported range for input alphabet is 1..={input_max_base}.\n"
400                )
401            };
402            return Ok(ToolResult::immediate_err(err_msg.into_bytes(), 1));
403        }
404        if !(1..=output_max_base).contains(&to) {
405            let err_msg = if to > 36 {
406                format!(
407                    "Base out of range (to: {to}). Bases > 36 (up to 64) require --output-alphabet base64_standard.\n"
408                )
409            } else {
410                format!(
411                    "Invalid base (to: {to}). Supported range for output alphabet is 1..={output_max_base}.\n"
412                )
413            };
414            return Ok(ToolResult::immediate_err(err_msg.into_bytes(), 1));
415        }
416        let input = match args.get(2..) {
417            Some(s) => s.join(" "),
418            None => String::new(),
419        };
420        (input, Some(from), Some(to))
421    } else if args.is_empty() {
422        anyhow::bail!(
423            "Invalid arguments! Usage: base2base [FROM_BASE TO_BASE INPUT] or [INPUT]"
424        );
425    } else if let [from_str, to_str] = args
426        && let (Ok(from), Ok(to)) =
427            (from_str.parse::<u8>(), to_str.parse::<u8>())
428    {
429        return Ok(ToolResult::immediate_err(
430            format!(
431                "Missing input string. Usage: base2base {from} {to} <INPUT...>\n"
432            )
433            .into_bytes(),
434            1,
435        ));
436    } else {
437        let input = args.join(" ");
438        (input, None, None)
439    };
440
441    run_base_convert(&from_base, &to_base, &input, base_args)
442}
443
444#[cfg(test)]
445#[allow(
446    clippy::panic,
447    clippy::expect_used,
448    clippy::unwrap_used,
449    clippy::unwrap_in_result,
450    clippy::panic_in_result_fn,
451    clippy::indexing_slicing,
452    clippy::arithmetic_side_effects,
453    reason = "Standard repository test boilerplate"
454)]
455mod tests {
456    use super::*;
457
458    #[crate::ctb_test]
459    fn test_base_args_default() {
460        let args = BaseArgs::default();
461        assert!(!args.bytes);
462        assert!(!args.no_pad);
463        assert_eq!(args.prefix, "");
464        assert_eq!(args.separator, " ");
465        assert!(args.lowercase);
466        assert!(args.filter_chars);
467        assert!(!args.collapse_filtered);
468        assert!(args.collapse_only.is_empty());
469        assert!(args.parse_prefixes);
470        assert_eq!(args.limit, 0);
471        assert!(!args.pad);
472        assert_eq!(args.pad_l, 1);
473        assert_eq!(args.input_alphabet, CliBaseAlphabet::Standard);
474        assert_eq!(args.output_alphabet, CliBaseAlphabet::Standard);
475        assert!(!args.quiet);
476    }
477
478    #[crate::ctb_test]
479    fn test_run_base2base_three_args() {
480        let args = vec!["16".to_string(), "10".to_string(), "1A".to_string()];
481        let base_args = BaseArgs::default();
482        let res = run_base2base(&args, &base_args).unwrap();
483        match res {
484            ToolResult::Immediate {
485                stdout, exit_code, ..
486            } => {
487                assert_eq!(exit_code, 0);
488                assert_eq!(String::from_utf8(stdout).unwrap().trim(), "26");
489            }
490            _ => panic!("Expected immediate result"),
491        }
492    }
493
494    #[crate::ctb_test]
495    fn test_run_base2base_two_args_error() {
496        let args = vec!["16".to_string(), "10".to_string()];
497        let base_args = BaseArgs::default();
498        let res = run_base2base(&args, &base_args).unwrap();
499        match res {
500            ToolResult::Immediate {
501                stderr, exit_code, ..
502            } => {
503                assert_eq!(exit_code, 1);
504                let err_msg = String::from_utf8(stderr).unwrap();
505                assert!(err_msg.contains("Missing input string"));
506            }
507            _ => panic!("Expected immediate result"),
508        }
509    }
510
511    #[crate::ctb_test]
512    fn test_run_base2base_single_arg_identity() {
513        let args = vec!["10 20".to_string()];
514        let base_args = BaseArgs::default();
515        let res = run_base2base(&args, &base_args).unwrap();
516        match res {
517            ToolResult::Immediate {
518                stdout, exit_code, ..
519            } => {
520                assert_eq!(exit_code, 0);
521                assert_eq!(String::from_utf8(stdout).unwrap().trim(), "10 20");
522            }
523            _ => panic!("Expected immediate result"),
524        }
525    }
526
527    #[crate::ctb_test]
528    fn test_run_base2base_base1() {
529        let base_args = BaseArgs::default();
530
531        let test_cases_to_base1 =
532            [("0", ""), ("1", "0"), ("2", "00"), ("3", "000")];
533        for (input, expected) in test_cases_to_base1 {
534            let args =
535                vec!["10".to_string(), "1".to_string(), input.to_string()];
536            let res = run_base2base(&args, &base_args).unwrap();
537            match res {
538                ToolResult::Immediate {
539                    stdout, exit_code, ..
540                } => {
541                    assert_eq!(exit_code, 0);
542                    // Output has trailing newline
543                    assert_eq!(
544                        String::from_utf8(stdout).unwrap(),
545                        format!("{expected}\n")
546                    );
547                }
548                _ => panic!("Expected immediate result"),
549            }
550        }
551
552        let test_cases_from_base1 =
553            [("", "0"), ("0", "1"), ("00", "2"), ("000", "3")];
554        for (input, expected) in test_cases_from_base1 {
555            let args =
556                vec!["1".to_string(), "10".to_string(), input.to_string()];
557            let res = run_base2base(&args, &base_args).unwrap();
558            match res {
559                ToolResult::Immediate {
560                    stdout, exit_code, ..
561                } => {
562                    assert_eq!(exit_code, 0);
563                    assert_eq!(
564                        String::from_utf8(stdout).unwrap(),
565                        format!("{expected}\n")
566                    );
567                }
568                _ => panic!("Expected immediate result"),
569            }
570        }
571    }
572
573    #[crate::ctb_test]
574    fn test_run_base_convert_bytes_shortcut() {
575        let base_args = BaseArgs {
576            bytes: true,
577            ..Default::default()
578        };
579        let res = run_base_convert(&Some(10), &Some(16), "255 16", &base_args)
580            .unwrap();
581        match res {
582            ToolResult::Immediate {
583                stdout, exit_code, ..
584            } => {
585                assert_eq!(exit_code, 0);
586                assert_eq!(String::from_utf8(stdout).unwrap().trim(), "ff 10");
587            }
588            _ => panic!("Expected immediate result"),
589        }
590    }
591
592    #[crate::ctb_test]
593    fn test_run_base_convert_no_pad_without_bytes_error() {
594        let base_args = BaseArgs {
595            no_pad: true,
596            ..Default::default()
597        };
598        let res =
599            run_base_convert(&Some(10), &Some(16), "255", &base_args).unwrap();
600        match res {
601            ToolResult::Immediate {
602                stderr, exit_code, ..
603            } => {
604                assert_eq!(exit_code, 1);
605                assert!(
606                    String::from_utf8(stderr)
607                        .unwrap()
608                        .contains("--no-pad is only valid with --bytes")
609                );
610            }
611            _ => panic!("Expected immediate result"),
612        }
613    }
614
615    #[crate::ctb_test]
616    fn test_base2base_positional_args() {
617        let args = vec![
618            "16".to_string(),
619            "2".to_string(),
620            "1f".to_string(),
621            "2a".to_string(),
622        ];
623        let base_args = BaseArgs {
624            bytes: false,
625            no_pad: false,
626            prefix: "0b".to_string(),
627            separator: " ".to_string(),
628            lowercase: true,
629            filter_chars: true,
630            collapse_filtered: false,
631            collapse_only: Vec::new(),
632            parse_prefixes: true,
633            limit: 0,
634            pad: false,
635            pad_l: 1,
636            input_alphabet: CliBaseAlphabet::Standard,
637            output_alphabet: CliBaseAlphabet::Standard,
638            quiet: false,
639        };
640        let res = run_base2base(&args, &base_args).unwrap();
641        match res {
642            ToolResult::Immediate {
643                stdout, exit_code, ..
644            } => {
645                assert_eq!(exit_code, 0);
646                let output = String::from_utf8(stdout).unwrap();
647                assert_eq!(output.trim(), "0b11111 0b101010");
648            }
649            _ => panic!("Expected Immediate ToolResult"),
650        }
651    }
652
653    #[crate::ctb_test]
654    fn test_base2base_base64_positional_args() {
655        let args = vec![
656            "10".to_string(),
657            "64".to_string(),
658            "0".to_string(),
659            "1".to_string(),
660            "63".to_string(),
661            "64".to_string(),
662            "255".to_string(),
663        ];
664        let base_args = BaseArgs {
665            bytes: false,
666            no_pad: false,
667            prefix: String::new(),
668            separator: " ".to_string(),
669            lowercase: false,
670            filter_chars: true,
671            collapse_filtered: false,
672            collapse_only: Vec::new(),
673            parse_prefixes: true,
674            limit: 0,
675            pad: false,
676            pad_l: 1,
677            input_alphabet: CliBaseAlphabet::Standard,
678            output_alphabet: CliBaseAlphabet::Base64Standard,
679            quiet: false,
680        };
681        let res = run_base2base(&args, &base_args).unwrap();
682        match res {
683            ToolResult::Immediate {
684                stdout, exit_code, ..
685            } => {
686                assert_eq!(exit_code, 0);
687                let output = String::from_utf8(stdout).unwrap();
688                assert_eq!(output.trim(), "A B / BA D/");
689            }
690            _ => panic!("Expected Immediate ToolResult"),
691        }
692    }
693
694    #[crate::ctb_test]
695    fn test_base2base_base30_base64_alphabet() {
696        let args =
697            vec!["10".to_string(), "30".to_string(), "25516010".to_string()];
698        let base_args = BaseArgs {
699            bytes: false,
700            no_pad: false,
701            prefix: String::new(),
702            separator: " ".to_string(),
703            lowercase: false,
704            filter_chars: true,
705            collapse_filtered: false,
706            collapse_only: Vec::new(),
707            parse_prefixes: true,
708            limit: 0,
709            pad: false,
710            pad_l: 1,
711            input_alphabet: CliBaseAlphabet::Standard,
712            output_alphabet: CliBaseAlphabet::Base64Standard,
713            quiet: false,
714        };
715        let res = run_base2base(&args, &base_args).unwrap();
716        match res {
717            ToolResult::Immediate {
718                stdout, exit_code, ..
719            } => {
720                assert_eq!(exit_code, 0);
721                let output = String::from_utf8(stdout).unwrap();
722                assert_eq!(output.trim(), "BBPBDU");
723            }
724            _ => panic!("Expected Immediate ToolResult"),
725        }
726
727        // Roundtrip back to base 10
728        let args_back =
729            vec!["30".to_string(), "10".to_string(), "BBPBDU".to_string()];
730        let base_args_back = BaseArgs {
731            bytes: false,
732            no_pad: false,
733            prefix: String::new(),
734            separator: " ".to_string(),
735            lowercase: false,
736            filter_chars: true,
737            collapse_filtered: false,
738            collapse_only: Vec::new(),
739            parse_prefixes: true,
740            limit: 0,
741            pad: false,
742            pad_l: 1,
743            input_alphabet: CliBaseAlphabet::Base64Standard,
744            output_alphabet: CliBaseAlphabet::Standard,
745            quiet: false,
746        };
747        let res_back = run_base2base(&args_back, &base_args_back).unwrap();
748        match res_back {
749            ToolResult::Immediate {
750                stdout, exit_code, ..
751            } => {
752                assert_eq!(exit_code, 0);
753                let output = String::from_utf8(stdout).unwrap();
754                assert_eq!(output.trim(), "25516010");
755            }
756            _ => panic!("Expected Immediate ToolResult"),
757        }
758    }
759
760    #[crate::ctb_test]
761    fn test_hex2dec_dec2hex_hexfmt_unquoted_and_continuous() {
762        // hex2dec with unquoted tokens
763        let res = run_base_convert(
764            &Some(16),
765            &Some(10),
766            "1A 2B 3C",
767            &BaseArgs::default(),
768        )
769        .unwrap();
770        match res {
771            ToolResult::Immediate {
772                stdout, exit_code, ..
773            } => {
774                assert_eq!(exit_code, 0);
775                assert_eq!(
776                    String::from_utf8(stdout).unwrap().trim(),
777                    "26 43 60"
778                );
779            }
780            _ => panic!("Expected Immediate ToolResult"),
781        }
782
783        // dec2hex with unquoted tokens
784        let res = run_base_convert(
785            &Some(10),
786            &Some(16),
787            "255 128 64",
788            &BaseArgs::default(),
789        )
790        .unwrap();
791        match res {
792            ToolResult::Immediate {
793                stdout, exit_code, ..
794            } => {
795                assert_eq!(exit_code, 0);
796                assert_eq!(
797                    String::from_utf8(stdout).unwrap().trim(),
798                    "ff 80 40"
799                );
800            }
801            _ => panic!("Expected Immediate ToolResult"),
802        }
803
804        // hexfmt with prefix
805        let base_args = BaseArgs {
806            prefix: "0x".to_string(),
807            ..Default::default()
808        };
809        let res = run_base_convert(&Some(16), &Some(16), "1a 2b", &base_args)
810            .unwrap();
811        match res {
812            ToolResult::Immediate {
813                stdout, exit_code, ..
814            } => {
815                assert_eq!(exit_code, 0);
816                assert_eq!(
817                    String::from_utf8(stdout).unwrap().trim(),
818                    "0x1a 0x2b"
819                );
820            }
821            _ => panic!("Expected Immediate ToolResult"),
822        }
823
824        // hex2dec continuous hex scalar vs bytes
825        let res_scalar = run_base_convert(
826            &Some(16),
827            &Some(10),
828            "deadbeef",
829            &BaseArgs::default(),
830        )
831        .unwrap();
832        match res_scalar {
833            ToolResult::Immediate {
834                stdout, exit_code, ..
835            } => {
836                assert_eq!(exit_code, 0);
837                assert_eq!(
838                    String::from_utf8(stdout).unwrap().trim(),
839                    "3735928559"
840                );
841            }
842            _ => panic!("Expected Immediate ToolResult"),
843        }
844
845        let base_args_bytes = BaseArgs {
846            bytes: true,
847            limit: 255,
848            pad: true,
849            ..Default::default()
850        };
851        let res_bytes = run_base_convert(
852            &Some(16),
853            &Some(10),
854            "deadbeef",
855            &base_args_bytes,
856        )
857        .unwrap();
858        match res_bytes {
859            ToolResult::Immediate {
860                stdout, exit_code, ..
861            } => {
862                assert_eq!(exit_code, 0);
863                assert_eq!(
864                    String::from_utf8(stdout).unwrap().trim(),
865                    "222 173 190 239"
866                );
867            }
868            _ => panic!("Expected Immediate ToolResult"),
869        }
870    }
871
872    #[crate::ctb_test]
873    fn test_hex2dec_dec2hex_hexfmt_unquoted_and_continuous_cli() -> Result<()> {
874        use ctb_formats_math::cli::BaseArgs;
875
876        // hex2dec with unquoted tokens
877        let res = super::run_base_convert(
878            &Some(16),
879            &Some(10),
880            "1A 2B 3C",
881            &BaseArgs::default(),
882        )?;
883        match res {
884            ToolResult::Immediate {
885                stdout, exit_code, ..
886            } => {
887                assert_eq!(exit_code, 0);
888                assert_eq!(String::from_utf8(stdout)?.trim(), "26 43 60");
889            }
890            _ => panic!("Expected Immediate ToolResult"),
891        }
892
893        // dec2hex with unquoted tokens
894        let res = super::run_base_convert(
895            &Some(10),
896            &Some(16),
897            "255 128 64",
898            &BaseArgs::default(),
899        )?;
900        match res {
901            ToolResult::Immediate {
902                stdout, exit_code, ..
903            } => {
904                assert_eq!(exit_code, 0);
905                assert_eq!(String::from_utf8(stdout)?.trim(), "ff 80 40");
906            }
907            _ => panic!("Expected Immediate ToolResult"),
908        }
909
910        // hexfmt with prefix
911        let res = super::run_base_convert(
912            &Some(16),
913            &Some(16),
914            "1a 2b",
915            &BaseArgs {
916                prefix: "0x".to_string(),
917                ..Default::default()
918            },
919        )?;
920        match res {
921            ToolResult::Immediate {
922                stdout, exit_code, ..
923            } => {
924                assert_eq!(exit_code, 0);
925                assert_eq!(String::from_utf8(stdout)?.trim(), "0x1a 0x2b");
926            }
927            _ => panic!("Expected Immediate ToolResult"),
928        }
929
930        // hex2dec continuous hex scalar vs bytes
931        let res_scalar = super::run_base_convert(
932            &Some(16),
933            &Some(10),
934            "deadbeef",
935            &BaseArgs::default(),
936        )?;
937        match res_scalar {
938            ToolResult::Immediate {
939                stdout, exit_code, ..
940            } => {
941                assert_eq!(exit_code, 0);
942                assert_eq!(String::from_utf8(stdout)?.trim(), "3735928559");
943            }
944            _ => panic!("Expected Immediate ToolResult"),
945        }
946
947        let res_bytes = super::run_base_convert(
948            &Some(16),
949            &Some(10),
950            "deadbeef",
951            &BaseArgs {
952                bytes: true,
953                limit: 255,
954                pad: true,
955                ..Default::default()
956            },
957        )?;
958        match res_bytes {
959            ToolResult::Immediate {
960                stdout, exit_code, ..
961            } => {
962                assert_eq!(exit_code, 0);
963                assert_eq!(
964                    String::from_utf8(stdout)?.trim(),
965                    "222 173 190 239"
966                );
967            }
968            _ => panic!("Expected Immediate ToolResult"),
969        }
970
971        Ok(())
972    }
973}