use std::fmt;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ErrorKind {
MissingHeaderParam,
InvalidHeaderParam,
UnsupportedMacAlgorithm,
InvalidMessage,
InvalidSignature,
Other,
}
#[derive(Clone, Debug)]
pub struct Error{
pub kind: ErrorKind,
pub message: String,
}
impl ErrorKind {
fn with_message(self, message: impl Into<String>) -> Error {
Error{kind: self, message: message.into()}
}
}
impl Error {
#![allow(non_upper_case_globals)]
pub const Other : ErrorKind = ErrorKind::Other;
pub const MissingHeaderParam : ErrorKind = ErrorKind::MissingHeaderParam;
pub const InvalidHeaderParam : ErrorKind = ErrorKind::InvalidHeaderParam;
pub const UnsupportedMacAlgorithm : ErrorKind = ErrorKind::UnsupportedMacAlgorithm;
pub const InvalidMessage : ErrorKind = ErrorKind::InvalidMessage;
pub const InvalidSignature : ErrorKind = ErrorKind::InvalidSignature;
pub fn kind(&self) -> ErrorKind {
self.kind
}
pub fn message(&self) -> &str {
&self.message
}
pub fn other(message: impl Into<String>) -> Self {
ErrorKind::Other.with_message(message)
}
pub fn missing_header_param(message: impl Into<String>) -> Self {
ErrorKind::MissingHeaderParam.with_message(message)
}
pub fn invalid_header_param(message: impl Into<String>) -> Self {
ErrorKind::InvalidHeaderParam.with_message(message)
}
pub fn unsupported_mac_algorithm(message: impl Into<String>) -> Self {
ErrorKind::UnsupportedMacAlgorithm.with_message(message)
}
pub fn invalid_message(message: impl Into<String>) -> Self {
ErrorKind::InvalidMessage.with_message(message)
}
pub fn invalid_signature(message: impl Into<String>) -> Self {
ErrorKind::InvalidSignature.with_message(message)
}
}
impl fmt::Display for ErrorKind {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
match self {
ErrorKind::Other => write!(formatter, "unspecified error"),
ErrorKind::MissingHeaderParam => write!(formatter, "missing header parameter"),
ErrorKind::InvalidHeaderParam => write!(formatter, "invalid header parameter"),
ErrorKind::UnsupportedMacAlgorithm => write!(formatter, "unsupported MAC algorithm"),
ErrorKind::InvalidMessage => write!(formatter, "invalid message"),
ErrorKind::InvalidSignature => write!(formatter, "invalid signature"),
}
}
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
if self.message.is_empty() {
write!(formatter, "{}", self.kind)
} else {
write!(formatter, "{}: {}", self.kind, self.message)
}
}
}
impl std::error::Error for Error {}