ndtensor/
error.rs

1/*
2    Appellation: error <module>
3    Contrib: @FL03
4*/
5//! This module implements the core [`TensorError`] type for the framework and provides a
6//! [`Result`] type alias for convenience.
7#[cfg(feature = "alloc")]
8use alloc::{
9    boxed::Box,
10    string::{String, ToString},
11};
12#[allow(dead_code)]
13/// a type alias for a [`Result`](core::result::Result) configured with the [`TensorError`] as
14/// its error type.
15pub(crate) type Result<T> = core::result::Result<T, TensorError>;
16
17/// The [`Error`] type enumerates various errors that can occur within the framework.
18#[derive(Debug, thiserror::Error)]
19pub enum TensorError {
20    #[error(transparent)]
21    ShapeError(#[from] ndarray::ShapeError),
22    #[cfg(feature = "anyhow")]
23    #[error(transparent)]
24    AnyError(#[from] anyhow::Error),
25    #[cfg(feature = "alloc")]
26    #[error(transparent)]
27    BoxError(#[from] Box<dyn core::error::Error + Send + Sync>),
28    #[cfg(feature = "serde")]
29    #[error(transparent)]
30    DeserializeError(#[from] serde::de::value::Error),
31    #[error(transparent)]
32    FmtError(#[from] core::fmt::Error),
33    #[cfg(feature = "serde_json")]
34    #[error(transparent)]
35    JsonError(#[from] serde_json::Error),
36    #[cfg(feature = "std")]
37    #[error(transparent)]
38    IoError(#[from] std::io::Error),
39    #[error(transparent)]
40    #[cfg(feature = "rand")]
41    UniformError(#[from] rand_distr::uniform::Error),
42    #[cfg(feature = "alloc")]
43    #[error("Unknown Error: {0}")]
44    Unknown(String),
45}
46
47#[cfg(feature = "alloc")]
48impl TensorError {
49    /// create a new [`BoxError`](Error::BoxError) variant using the given error
50    pub fn box_error<E>(error: E) -> Self
51    where
52        E: 'static + Send + Sync + core::error::Error,
53    {
54        Self::BoxError(Box::new(error))
55    }
56    /// create a new [`Unknown`](Error::Unknown) variant using the given string
57    pub fn unknown<S>(error: S) -> Self
58    where
59        S: ToString,
60    {
61        Self::Unknown(error.to_string())
62    }
63}
64
65#[cfg(feature = "alloc")]
66impl From<String> for TensorError {
67    fn from(value: String) -> Self {
68        Self::Unknown(value)
69    }
70}
71
72#[cfg(feature = "alloc")]
73impl From<&str> for TensorError {
74    fn from(value: &str) -> Self {
75        Self::Unknown(String::from(value))
76    }
77}