From 6649470ff7009dab56dea820a81b95318ff060bb Mon Sep 17 00:00:00 2001 From: PlexSheep Date: Mon, 13 May 2024 13:51:17 +0200 Subject: [PATCH] refactor: numf_parser takes a generic unsigned int #13 --- Cargo.toml | 1 + src/format.rs | 22 ++++++++++++++-------- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 835d278..d848183 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,4 +19,5 @@ clap = { version = "4.5.4", features = ["derive"] } clap-num = "1.1.1" fast32 = "1.0.2" libpt = { version = "0.5.0", features = ["bintols"]} +num = "0.4.3" diff --git a/src/format.rs b/src/format.rs index 38470f0..30c41d3 100644 --- a/src/format.rs +++ b/src/format.rs @@ -1,8 +1,8 @@ -#![allow(dead_code)] +#![allow(dead_code)] // this is exported to lib.rs use anyhow::anyhow; -// this is exported to lib.rs use clap::{ArgGroup, Parser}; use libpt::bintols::split; +use num; pub type NumberType = u128; @@ -69,7 +69,7 @@ pub struct FormatOptions { #[arg(short = 'z', long)] /// format to base32 base32: bool, - #[clap(value_parser=numf_parser, required=true)] + #[clap(value_parser=numf_parser::, required=true)] /// at least one number that should be formatted /// /// supports either base 10 or base 16 inputs (with 0xaaaa) @@ -238,8 +238,14 @@ impl Format { /// let args = Args::parse_from(&["", "-a", "0x10"]); /// assert_eq!(args.address, 16); /// ``` -pub fn numf_parser(s: &str) -> anyhow::Result { - if s.starts_with(&Format::Dec.prefix()) || s.parse::().is_ok() { +pub fn numf_parser(s: &str) -> anyhow::Result +where + T: std::str::FromStr, + ::Err: std::fmt::Display, + T: num::Num, + ::FromStrRadixErr: std::fmt::Display, +{ + if s.starts_with(&Format::Dec.prefix()) || s.parse::().is_ok() { let s = match s.strip_prefix(&Format::Dec.prefix()) { Some(sr) => sr, None => s, @@ -256,7 +262,7 @@ pub fn numf_parser(s: &str) -> anyhow::Result { Some(sr) => sr, None => s, }; - match NumberType::from_str_radix(s, 16) { + match T::from_str_radix(s, 16) { Ok(r) => Ok(r), Err(e) => { let e = format!("{e}"); @@ -268,7 +274,7 @@ pub fn numf_parser(s: &str) -> anyhow::Result { Some(sr) => sr, None => s, }; - match NumberType::from_str_radix(s, 8) { + match T::from_str_radix(s, 8) { Ok(r) => Ok(r), Err(e) => { let e = format!("{e}"); @@ -280,7 +286,7 @@ pub fn numf_parser(s: &str) -> anyhow::Result { Some(sr) => sr, None => s, }; - match NumberType::from_str_radix(s, 2) { + match T::from_str_radix(s, 2) { Ok(r) => Ok(r), Err(e) => { let e = format!("{e}");