How do you implement a parser for a custom type that is fallible? #5416
-
I am trying to implement a customer non-unit enum type for parsing memory/storage requests. The idea being that it takes a string Clap Version: 4.4.18 #[derive(Debug, Args)]
#[command(args_conflicts_with_subcommands = false)]
pub struct TuneCommand {
#[arg(
help = "Amount of memory to provide postgres. ie: '32GB'. (default system memory)"
)]
memory_limit: Option<StorageUnit>,
}
#[derive(Debug, Clone)]
pub enum StorageUnit {
B(u64),
KiB(u64),
MiB(u64),
GiB(u64),
TiB(u64),
}
impl From<&str> for StorageUnit {
fn from(s: &str) -> Self {
let value: u64 = s.trim_end_matches(char::is_alphabetic).parse().unwrap();
let unit = s.trim_start_matches(char::is_numeric);
match unit {
"" => StorageUnit::B(value),
"kB" => StorageUnit::KiB(value),
"MB" => StorageUnit::MiB(value),
"GB" => StorageUnit::GiB(value),
"TB" => StorageUnit::TiB(value),
_ => panic!("Invalid amount of storage"),
}
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
How we pick the parser for a field is implemented by |
Beta Was this translation helpful? Give feedback.
Alright got it working. For some reason adding
impl Display
to myFromStr
Error
type didn't work but making the value parser function forcibly return aString
error withResult<StorageUnit, String>
did.