styled_str/ansi_parser/
errors.rs

1use alloc::string::String;
2use core::{fmt, num::ParseIntError, str::Utf8Error};
3
4/// Errors that can occur when processing terminal output.
5#[derive(Debug)]
6#[non_exhaustive]
7pub enum AnsiError {
8    /// Unfinished escape sequence.
9    UnfinishedSequence,
10    /// Unrecognized escape sequence (not a CSI or OSC one). The enclosed byte
11    /// is the first byte of the sequence (excluding `0x1b`).
12    UnrecognizedSequence(u8),
13    /// Invalid final byte for an SGR escape sequence.
14    InvalidSgrFinalByte(u8),
15    /// Unfinished color spec.
16    UnfinishedColor,
17    /// Invalid type of a color spec.
18    InvalidColorType(String),
19    /// Invalid ANSI color index.
20    InvalidColorIndex(ParseIntError),
21    /// UTF-8 decoding error.
22    Utf8(Utf8Error),
23}
24
25impl fmt::Display for AnsiError {
26    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
27        match self {
28            Self::UnfinishedSequence => formatter.write_str("Unfinished ANSI escape sequence"),
29            Self::UnrecognizedSequence(byte) => {
30                write!(
31                    formatter,
32                    "Unrecognized escape sequence (first byte is {byte})"
33                )
34            }
35            Self::InvalidSgrFinalByte(byte) => {
36                write!(
37                    formatter,
38                    "Invalid final byte for an SGR escape sequence: {byte}"
39                )
40            }
41            Self::UnfinishedColor => formatter.write_str("Unfinished color spec"),
42            Self::InvalidColorType(ty) => {
43                write!(formatter, "Invalid type of a color spec: {ty}")
44            }
45            Self::InvalidColorIndex(err) => {
46                write!(formatter, "Failed parsing color index: {err}")
47            }
48            Self::Utf8(err) => write!(formatter, "UTF-8 decoding error: {err}"),
49        }
50    }
51}
52
53impl core::error::Error for AnsiError {
54    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
55        match self {
56            Self::InvalidColorIndex(err) => Some(err),
57            Self::Utf8(err) => Some(err),
58            _ => None,
59        }
60    }
61}
62
63impl From<Utf8Error> for AnsiError {
64    fn from(err: Utf8Error) -> Self {
65        Self::Utf8(err)
66    }
67}