rstm_core/
error.rs

1/*
2    Appellation: error <module>
3    Contrib: FL03 <jo3mccain@icloud.com>
4*/
5//! The [`error`](self) module defines the core [`Error`] type used throughout the library and
6//! provides a convenient alias for [`Result`](core::result::Result) types.
7#[cfg(feature = "alloc")]
8use alloc::{boxed::Box, string::String};
9
10/// A type alias for a [`Result`](core::result::Result) with an error type of [`Error`]
11pub type Result<T = ()> = core::result::Result<T, self::Error>;
12
13/// The [`Error`] implementation describes the various errors that can occur within the library
14#[derive(Debug, thiserror::Error)]
15#[non_exhaustive]
16pub enum Error {
17    #[error("The specified index ({index}) is out of bounds for a collection of {len} elements.")]
18    IndexOutOfBounds { index: usize, len: usize },
19    #[cfg(feature = "alloc")]
20    #[error("An unknown error occurred: {0}")]
21    Unknown(String),
22    #[cfg(feature = "alloc")]
23    #[error(transparent)]
24    BoxError(#[from] Box<dyn core::error::Error + Send + Sync + 'static>),
25    #[error(transparent)]
26    FmtError(#[from] core::fmt::Error),
27    #[cfg(feature = "std")]
28    #[error(transparent)]
29    IOError(#[from] std::io::Error),
30    #[error(transparent)]
31    #[cfg(feature = "serde_json")]
32    JsonError(#[from] serde_json::Error),
33    #[error(transparent)]
34    StateError(#[from] rstm_state::StateError),
35}
36
37impl Error {
38    /// returns an [`IndedOutOfBounds`](Error::IndexOutOfBounds) variant
39    pub const fn index_out_of_bounds(index: usize, len: usize) -> Self {
40        Self::IndexOutOfBounds { index, len }
41    }
42}
43
44#[cfg(feature = "alloc")]
45impl From<&str> for Error {
46    fn from(err: &str) -> Self {
47        Error::Unknown(String::from(err))
48    }
49}
50
51#[cfg(feature = "alloc")]
52impl From<String> for Error {
53    fn from(err: String) -> Self {
54        Error::Unknown(err)
55    }
56}