1use core::fmt::{self, Debug, Display};
4
5#[cfg(feature = "std")]
6use std::boxed::Box;
7
8pub type Result<T> = core::result::Result<T, Error>;
12
13#[derive(Default)]
25#[non_exhaustive]
26pub struct Error {
27    #[cfg(feature = "std")]
29    source: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
30}
31
32impl Error {
33    pub fn new() -> Self {
35        Self::default()
36    }
37
38    #[cfg(feature = "std")]
45    pub fn from_source(
46        source: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
47    ) -> Self {
48        Self {
49            source: Some(source.into()),
50        }
51    }
52}
53
54impl Debug for Error {
55    #[cfg(not(feature = "std"))]
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        f.write_str("signature::Error {}")
58    }
59
60    #[cfg(feature = "std")]
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        f.write_str("signature::Error { source: ")?;
63
64        if let Some(source) = &self.source {
65            write!(f, "Some({})", source)?;
66        } else {
67            f.write_str("None")?;
68        }
69
70        f.write_str(" }")
71    }
72}
73
74impl Display for Error {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        f.write_str("signature error")?;
77
78        #[cfg(feature = "std")]
79        {
80            if let Some(source) = &self.source {
81                write!(f, ": {}", source)?;
82            }
83        }
84
85        Ok(())
86    }
87}
88
89#[cfg(feature = "std")]
90impl From<Box<dyn std::error::Error + Send + Sync + 'static>> for Error {
91    fn from(source: Box<dyn std::error::Error + Send + Sync + 'static>) -> Error {
92        Self::from_source(source)
93    }
94}
95
96#[cfg(feature = "rand_core")]
97impl From<rand_core::Error> for Error {
98    #[cfg(not(feature = "std"))]
99    fn from(_source: rand_core::Error) -> Error {
100        Error::new()
101    }
102
103    #[cfg(feature = "std")]
104    fn from(source: rand_core::Error) -> Error {
105        Error::from_source(source)
106    }
107}
108
109#[cfg(feature = "std")]
110impl std::error::Error for Error {
111    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
112        self.source
113            .as_ref()
114            .map(|source| source.as_ref() as &(dyn std::error::Error + 'static))
115    }
116}