use crate::consts::KeyNumber;
use core::fmt::{self, Display};
#[cfg(feature = "std")]
extern crate std;
#[derive(Debug, PartialEq, Eq)]
pub enum Error {
InsufficentData,
InvalidFormat(FormatError),
UnsupportedAlgorithm,
MismatchedKey {
expected: KeyNumber,
found: KeyNumber,
},
WrongKey,
BadSignature,
BadPassword,
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::InsufficentData => f.write_str("insufficent data while parsing structure"),
Error::InvalidFormat(e) => Display::fmt(e, f),
Error::UnsupportedAlgorithm => f.write_str("encountered unsupported key algorithm"),
Error::MismatchedKey { expected, found } => {
write!(f,
"failed to verify signature: the wrong key was used. Expected {:?}, but found {:?}",
expected,
found,
)
}
Error::WrongKey => f.write_str("public key does not belong to the private key"),
Error::BadSignature => f.write_str("signature verification failed"),
Error::BadPassword => f.write_str("password was empty or incorrect for key"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for Error {}
#[derive(Debug, PartialEq, Eq)]
pub enum FormatError {
LineLength,
Comment {
expected: &'static str,
},
MissingNewline,
Base64,
}
impl Display for FormatError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
FormatError::LineLength => {
f.write_str("encountered an invalidly formatted line of data")
}
FormatError::Comment { expected } => {
write!(f, "line missing comment; expected {}", expected)
}
FormatError::MissingNewline => f.write_str("expected newline was not found"),
FormatError::Base64 => f.write_str("encountered invalid base64 data"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for FormatError {}
impl From<FormatError> for Error {
fn from(e: FormatError) -> Self {
Self::InvalidFormat(e)
}
}
#[cfg(test)]
mod tests {
use super::*;
use core::fmt::{Debug, Display};
use static_assertions::assert_impl_all;
#[cfg(feature = "std")]
assert_impl_all!(Error: std::error::Error);
#[cfg(feature = "std")]
assert_impl_all!(FormatError: std::error::Error);
assert_impl_all!(Error: Debug, Display, PartialEq, Send, Sync);
assert_impl_all!(FormatError: Debug, Display, PartialEq, Send, Sync);
}