diff --git a/Cargo.lock b/Cargo.lock index 2090d36d2..b7af3e20e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1435,6 +1435,9 @@ checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" [[package]] name = "option_parser" version = "0.1.0" +dependencies = [ + "thiserror 2.0.6", +] [[package]] name = "ordered-stream" diff --git a/option_parser/Cargo.toml b/option_parser/Cargo.toml index 23fbd4752..fc3129a70 100644 --- a/option_parser/Cargo.toml +++ b/option_parser/Cargo.toml @@ -3,3 +3,6 @@ authors = ["The Cloud Hypervisor Authors"] edition = "2021" name = "option_parser" version = "0.1.0" + +[dependencies] +thiserror = "2.0.6" diff --git a/option_parser/src/lib.rs b/option_parser/src/lib.rs index 54f97ee29..2d4cce017 100644 --- a/option_parser/src/lib.rs +++ b/option_parser/src/lib.rs @@ -4,10 +4,11 @@ // use std::collections::HashMap; -use std::fmt; use std::num::ParseIntError; use std::str::FromStr; +use thiserror::Error; + #[derive(Default)] pub struct OptionParser { options: HashMap, @@ -18,26 +19,17 @@ struct OptionParserValue { requires_value: bool, } -#[derive(Debug)] +#[derive(Error, Debug)] pub enum OptionParserError { + #[error("unknown option: {0}")] UnknownOption(String), + #[error("unknown option: {0}")] InvalidSyntax(String), - Conversion(String, String), + #[error("unable to convert {1} for {0}")] + Conversion(String /* field */, String /* value */), + #[error("invalid value: {0}")] InvalidValue(String), } - -impl fmt::Display for OptionParserError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - OptionParserError::UnknownOption(s) => write!(f, "unknown option: {s}"), - OptionParserError::InvalidSyntax(s) => write!(f, "invalid syntax:{s}"), - OptionParserError::Conversion(field, value) => { - write!(f, "unable to convert {value} for {field}") - } - OptionParserError::InvalidValue(s) => write!(f, "invalid value: {s}"), - } - } -} type OptionParserResult = std::result::Result; fn split_commas(s: &str) -> OptionParserResult> {