serde_jam/
error.rs

1//! general errors
2
3use crate::String;
4use core::fmt::Display;
5
6/// Error type for serde-jam
7#[derive(Debug)]
8pub enum Error {
9    /// Any error from `anyhow`
10    Anyhow(anyhow::Error),
11    /// Invalid length
12    InvalidLength {
13        /// Expected length
14        expected: usize,
15        /// Got length
16        got: usize,
17    },
18    /// Invalid input
19    InvalidInput(String),
20}
21
22impl core::fmt::Display for Error {
23    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
24        match self {
25            Self::Anyhow(e) => e.fmt(f),
26            Self::InvalidLength { expected, got } => {
27                write!(f, "Invalid length: expected {expected}, got {got}")
28            }
29            Self::InvalidInput(s) => write!(f, "Invalid input: {s}"),
30        }
31    }
32}
33
34impl core::error::Error for Error {
35    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
36        match self {
37            Self::Anyhow(e) => e.source(),
38            _ => None,
39        }
40    }
41}
42
43impl serde::ser::Error for Error {
44    fn custom<T: Display>(msg: T) -> Self {
45        Self::Anyhow(anyhow::anyhow!("{msg}"))
46    }
47}
48
49impl serde::de::Error for Error {
50    fn custom<T: Display>(msg: T) -> Self {
51        Self::Anyhow(anyhow::anyhow!("{msg}"))
52    }
53}
54
55impl From<anyhow::Error> for Error {
56    fn from(err: anyhow::Error) -> Self {
57        Self::Anyhow(err)
58    }
59}
60
61/// Result type for serde-jam
62pub type Result<T> = core::result::Result<T, Error>;