use core::{fmt, num::ParseIntError, str::Utf8Error};
use crate::alloc::String;
#[derive(Debug)]
#[non_exhaustive]
pub enum AnsiError {
UnfinishedSequence,
UnrecognizedSequence(u8),
InvalidSgrFinalByte(u8),
UnfinishedColor,
InvalidColorType(String),
InvalidColorIndex(ParseIntError),
Utf8(Utf8Error),
}
impl fmt::Display for AnsiError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnfinishedSequence => formatter.write_str("Unfinished ANSI escape sequence"),
Self::UnrecognizedSequence(byte) => {
write!(
formatter,
"Unrecognized escape sequence (first byte is {byte})"
)
}
Self::InvalidSgrFinalByte(byte) => {
write!(
formatter,
"Invalid final byte for an SGR escape sequence: {byte}"
)
}
Self::UnfinishedColor => formatter.write_str("Unfinished color spec"),
Self::InvalidColorType(ty) => {
write!(formatter, "Invalid type of a color spec: {ty}")
}
Self::InvalidColorIndex(err) => {
write!(formatter, "Failed parsing color index: {err}")
}
Self::Utf8(err) => write!(formatter, "UTF-8 decoding error: {err}"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for AnsiError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::InvalidColorIndex(err) => Some(err),
Self::Utf8(err) => Some(err),
_ => None,
}
}
}
impl From<Utf8Error> for AnsiError {
fn from(err: Utf8Error) -> Self {
Self::Utf8(err)
}
}