Skip to main content

cheetah_string/
error.rs

1use core::fmt;
2use core::str::Utf8Error;
3
4/// Compatibility error type for range operations and explicit conversions.
5///
6/// [`CheetahString::try_substring`](crate::CheetahString::try_substring) returns
7/// this type through the crate's [`Result`](crate::Result) alias. UTF-8 text
8/// constructors return [`Utf8Error`] directly; `Utf8Error` can still be wrapped
9/// through [`From`] for source-compatible 3.1 error aggregation.
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub enum Error {
12    /// UTF-8 validation failed.
13    Utf8Error(Utf8Error),
14    /// An index was beyond the string length.
15    IndexOutOfBounds {
16        /// Requested byte index.
17        index: usize,
18        /// String length in bytes.
19        len: usize,
20    },
21    /// A range started after its end.
22    InvalidRange {
23        /// Requested inclusive start index.
24        start: usize,
25        /// Requested exclusive end index.
26        end: usize,
27    },
28    /// An index did not lie on a UTF-8 character boundary.
29    InvalidCharBoundary {
30        /// Requested byte index.
31        index: usize,
32    },
33}
34
35impl fmt::Display for Error {
36    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
37        match self {
38            Error::Utf8Error(e) => write!(f, "UTF-8 error: {}", e),
39            Error::IndexOutOfBounds { index, len } => {
40                write!(f, "index {} out of bounds (len: {})", index, len)
41            }
42            Error::InvalidRange { start, end } => {
43                write!(f, "range start {} is greater than end {}", start, end)
44            }
45            Error::InvalidCharBoundary { index } => {
46                write!(f, "index {} is not a char boundary", index)
47            }
48        }
49    }
50}
51
52#[cfg(feature = "std")]
53impl std::error::Error for Error {
54    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
55        match self {
56            Error::Utf8Error(e) => Some(e),
57            _ => None,
58        }
59    }
60}
61
62impl From<Utf8Error> for Error {
63    fn from(e: Utf8Error) -> Self {
64        Error::Utf8Error(e)
65    }
66}
67
68/// Result type for `CheetahString` operations.
69pub type Result<T> = core::result::Result<T, Error>;