ansi_color_codec/
error.rs

1use std::fmt::{Display, Formatter};
2use std::num::ParseIntError;
3
4/// Encoding and decoding errors.
5#[derive(Clone, Debug, Eq, PartialEq)]
6pub enum Error {
7    /// The input byte stream terminated prematurely.
8    ByteStreamTerminatedUnexpectedly,
9    /// An invalid color code value has been encountered.
10    InvalidCodeValue(ParseIntError),
11    /// The prefix of the color code number was invalid.
12    InvalidNumberPrefix(u8),
13    /// An invalid start byte has been encountered.
14    InvalidStartByte(u8),
15    /// The second color code block is missing.
16    MissingSecondColorCodeBlock,
17    /// No digits for the color code number were found.
18    NoCodeDigitsFound,
19    /// Too many digits for the color code have been encountered.
20    TooManyCodeDigits {
21        /// Number of digits that have been processed.
22        at_least: u8,
23        /// Number of digits that were expected.
24        max: u8,
25    },
26    /// An unexpected byte has been encountered.
27    UnexpectedByte(u8),
28    /// The given color code value was out of bounds.
29    ValueOutOfBounds(u8),
30}
31
32impl Display for Error {
33    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
34        match self {
35            Self::ByteStreamTerminatedUnexpectedly => {
36                write!(f, "byte stream terminated unexpectedly")
37            }
38            Self::InvalidCodeValue(value) => write!(f, "invalid code value: {value}"),
39            Self::InvalidNumberPrefix(prefix) => write!(f, "invalid number prefix: {prefix}"),
40            Self::InvalidStartByte(byte) => write!(f, "invalid start byte: {byte:?}"),
41            Self::MissingSecondColorCodeBlock => write!(f, "missing second code block"),
42            Self::NoCodeDigitsFound => write!(f, "no code digits found"),
43            Self::TooManyCodeDigits { at_least, max } => {
44                write!(f, "too many code digits found: {at_least}+ / {max}")
45            }
46            Self::UnexpectedByte(byte) => write!(f, "unexpected byte: {byte:?}"),
47            Self::ValueOutOfBounds(value) => write!(f, "value out of bounds: {value}"),
48        }
49    }
50}
51
52impl std::error::Error for Error {
53    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
54        if let Self::InvalidCodeValue(error) = self {
55            Some(error)
56        } else {
57            None
58        }
59    }
60}