error.rs
1 use std::fmt; 2 3 #[derive(Debug, Clone, PartialEq, Eq)] 4 pub enum Error { 5 InvalidUtf8 { offset: usize, reason: String }, 6 UnclosedQuote { quote_type: &'static str, offset: usize }, 7 InvalidKey { offset: usize, reason: String }, 8 ForbiddenWhitespace { location: &'static str, offset: usize }, 9 DoubleEquals { offset: usize }, 10 InvalidBom { offset: usize }, 11 Expected { offset: usize, expected: &'static str }, 12 Generic { offset: usize, message: String }, 13 Io(String), 14 } 15 16 impl Error { 17 pub fn offset(&self) -> usize { 18 match self { 19 Error::InvalidUtf8 { offset, .. } => *offset, 20 Error::UnclosedQuote { offset, .. } => *offset, 21 Error::InvalidKey { offset, .. } => *offset, 22 Error::ForbiddenWhitespace { offset, .. } => *offset, 23 Error::DoubleEquals { offset } => *offset, 24 Error::InvalidBom { offset } => *offset, 25 Error::Expected { offset, .. } => *offset, 26 Error::Generic { offset, .. } => *offset, 27 Error::Io(_) => 0, 28 } 29 } 30 } 31 32 impl fmt::Display for Error { 33 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 34 match self { 35 Error::InvalidUtf8 { offset, reason } => write!(f, "Invalid UTF-8 at byte {}: {}", offset, reason), 36 Error::UnclosedQuote { quote_type, offset } => write!(f, "Unclosed {} quote starting at byte {}", quote_type, offset), 37 Error::InvalidKey { offset, reason } => write!(f, "Invalid key at byte {}: {}", offset, reason), 38 Error::ForbiddenWhitespace { location, offset } => write!(f, "Whitespace not allowed {} at byte {}", location, offset), 39 Error::DoubleEquals { offset } => write!(f, "Double equals sign detected at byte {}. Use quotes: KEY=\"=val\"", offset), 40 Error::InvalidBom { offset } => write!(f, "BOM found at invalid position (byte {})", offset), 41 Error::Expected { offset, expected } => write!(f, "Expected {} at byte {}", expected, offset), 42 Error::Generic { offset, message } => write!(f, "{} at byte {}", message, offset), 43 Error::Io(msg) => write!(f, "IO Error: {}", msg), 44 } 45 } 46 } 47 48 impl std::error::Error for Error {}