//! Encoding error types. use std::fmt; /// Errors that can occur during encoding/decoding operations. #[derive(Debug, Clone, PartialEq, Eq)] pub enum EncodingError { /// An invalid byte sequence was encountered in fatal (strict) mode. InvalidSequence { encoding: &'static str, position: usize, }, /// The requested encoding label is not recognized. UnknownLabel(String), /// The encoding does not support the encode operation. /// Per WHATWG spec, UTF-16BE/LE are decode-only. EncodeNotSupported { encoding: &'static str }, } impl fmt::Display for EncodingError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::InvalidSequence { encoding, position } => { write!( f, "invalid byte sequence in {encoding} at position {position}" ) } Self::UnknownLabel(label) => { write!(f, "unknown encoding label: {label}") } Self::EncodeNotSupported { encoding } => { write!(f, "encode not supported for {encoding}") } } } } pub type Result = std::result::Result; #[cfg(test)] mod tests { use super::*; #[test] fn display_invalid_sequence() { let err = EncodingError::InvalidSequence { encoding: "UTF-8", position: 5, }; assert_eq!( err.to_string(), "invalid byte sequence in UTF-8 at position 5" ); } #[test] fn display_unknown_label() { let err = EncodingError::UnknownLabel("bogus".to_string()); assert_eq!(err.to_string(), "unknown encoding label: bogus"); } #[test] fn display_encode_not_supported() { let err = EncodingError::EncodeNotSupported { encoding: "UTF-16LE", }; assert_eq!(err.to_string(), "encode not supported for UTF-16LE"); } }