use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
#[error("Key generation failed: {0}")]
Generation(#[from] GenerationError),
#[error("Validation failed: {0}")]
Validation(#[from] ValidationError),
}
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Error)]
pub enum GenerationError {
#[error("Identity generation failed")]
IdentityCreationFailed,
}
#[derive(Debug, Error)]
pub enum ValidationError {
#[error("Invalid public key format: {reason}")]
InvalidPublicKeyFormat {
reason: String,
},
#[error("Invalid secret key format: {reason}")]
InvalidSecretKeyFormat {
reason: String,
},
}
impl ValidationError {
pub(crate) fn invalid_public_key(reason: impl Into<String>) -> Self {
Self::InvalidPublicKeyFormat {
reason: reason.into(),
}
}
pub(crate) fn invalid_secret_key(reason: impl Into<String>) -> Self {
Self::InvalidSecretKeyFormat {
reason: reason.into(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn generation_error_conversion() {
let gen_err = GenerationError::IdentityCreationFailed;
let err: Error = gen_err.into();
assert!(matches!(err, Error::Generation(_)));
}
#[test]
fn validation_error_conversion() {
let val_err = ValidationError::invalid_public_key("test");
let err: Error = val_err.into();
assert!(matches!(err, Error::Validation(_)));
}
#[test]
fn generation_error_display() {
let e = GenerationError::IdentityCreationFailed;
assert_eq!(format!("{}", e), "Identity generation failed");
}
#[test]
fn validation_error_display_public() {
let e = ValidationError::invalid_public_key("too short");
assert_eq!(format!("{}", e), "Invalid public key format: too short");
}
#[test]
fn validation_error_display_secret() {
let e = ValidationError::invalid_secret_key("empty");
assert_eq!(format!("{}", e), "Invalid secret key format: empty");
}
#[test]
fn result_type_alias() {
fn returns_ok() -> Result<()> {
Ok(())
}
fn returns_err() -> Result<()> {
Err(Error::Generation(GenerationError::IdentityCreationFailed))
}
assert!(returns_ok().is_ok());
assert!(returns_err().is_err());
}
}