1use std::fmt;
10
11#[derive(Debug, Clone, PartialEq, Eq)]
13pub enum Error {
14 InvalidKeyLength {
16 label: &'static str,
17 expected: usize,
18 got: usize,
19 },
20 InvalidPrefix { label: &'static str },
22 TooShort { label: &'static str },
24 MacVerificationFailed { label: &'static str },
26 DecryptionFailed { label: &'static str },
28 EncryptionFailed { label: &'static str },
30 UnknownIdentifier {
32 kind: &'static str,
33 identifier: String,
34 },
35 InvalidMasterKey { got: usize },
37 InvalidKey { label: &'static str },
39 InvalidIterations,
41 InvalidOutputLength { requested: usize, max: usize },
43 InvalidHex,
45 UnsupportedNationalAlgorithm {
47 name: &'static str,
48 hint: &'static str,
49 },
50}
51
52impl fmt::Display for Error {
53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54 match self {
55 Error::InvalidKeyLength {
56 label,
57 expected,
58 got,
59 } => write!(
60 f,
61 "{label} key must be exactly {expected} bytes (got {got})."
62 ),
63 Error::InvalidPrefix { label } => write!(f, "Invalid {label} ciphertext prefix."),
64 Error::TooShort { label } => write!(f, "{label} ciphertext too short."),
65 Error::MacVerificationFailed { label } => write!(f, "{label} MAC verification failed."),
66 Error::DecryptionFailed { label } => write!(f, "{label} decryption failed."),
67 Error::EncryptionFailed { label } => write!(f, "{label} encryption failed."),
68 Error::UnknownIdentifier { kind, identifier } => {
69 write!(f, "Unknown {kind} identifier \"{identifier}\".")
70 }
71 Error::InvalidMasterKey { got } => {
72 write!(f, "Master key must be exactly 32 bytes (got {got}).")
73 }
74 Error::InvalidKey { label } => write!(f, "Invalid {label} key."),
75 Error::InvalidIterations => write!(f, "PBKDF2 iterations must be positive."),
76 Error::InvalidOutputLength { requested, max } => {
77 if *requested == 0 {
78 write!(f, "Output length must be positive.")
79 } else {
80 write!(f, "Output length {requested} exceeds the maximum of {max}.")
81 }
82 }
83 Error::InvalidHex => write!(f, "Invalid hex string."),
84 Error::UnsupportedNationalAlgorithm { name, hint } => {
85 write!(f, "{name} is not provided by this library: {hint}")
86 }
87 }
88 }
89}
90
91impl std::error::Error for Error {}
92
93pub type Result<T> = std::result::Result<T, Error>;