diff --git a/rust/onepass/src/err.rs b/rust/onepass/src/err.rs index 451846d..5954a16 100644 --- a/rust/onepass/src/err.rs +++ b/rust/onepass/src/err.rs @@ -1,5 +1,5 @@ /// Represents the type of minification error. -#[derive(Debug, Eq, PartialEq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub enum ErrorType { ClosingTagMismatch { expected: String, got: String }, NotFound(&'static str), @@ -7,36 +7,41 @@ pub enum ErrorType { UnexpectedClosingTag, } -impl ErrorType { - /// Generates an English message describing the error with any additional context. - pub fn message(self) -> String { +impl std::fmt::Display for ErrorType { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ErrorType::ClosingTagMismatch { expected, got } => { - format!( - "Closing tag name does not match opening tag (expected \"{}\", got \"{}\").", + write!(f, + "closing tag name does not match opening tag (expected \"{}\", got \"{}\")", expected, got ) } ErrorType::NotFound(exp) => { - format!("Expected {}.", exp) + write!(f, "expected {}", exp) } ErrorType::UnexpectedEnd => { - format!("Unexpected end of source code.") + f.write_str("unexpected end of source code") } ErrorType::UnexpectedClosingTag => { - format!("Unexpected closing tag.") + f.write_str("unexpected closing tag") } } } } /// Details about a minification failure, including where it occurred and why. -#[derive(Debug)] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct Error { pub error_type: ErrorType, pub position: usize, } +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "At {}, {}", self.position, self.error_type) + } +} + /// User-friendly details about a minification failure, including an English message description of /// the reason, and generated printable contextual representation of the code where the error /// occurred. diff --git a/rust/onepass/src/lib.rs b/rust/onepass/src/lib.rs index 0341495..b9defc1 100644 --- a/rust/onepass/src/lib.rs +++ b/rust/onepass/src/lib.rs @@ -189,7 +189,7 @@ pub fn copy(code: &[u8], cfg: &Cfg) -> Result, Error> { pub fn with_friendly_error(code: &mut [u8], cfg: &Cfg) -> Result { in_place(code, cfg).map_err(|err| FriendlyError { position: err.position, - message: err.error_type.message(), + message: err.error_type.to_string(), code_context: debug_repr(code, err.position as isize, -1), }) }