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 MissingConfig { key: &'static str },
52}
53
54impl fmt::Display for Error {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 match self {
57 Error::InvalidKeyLength {
58 label,
59 expected,
60 got,
61 } => write!(
62 f,
63 "{label} key must be exactly {expected} bytes (got {got})."
64 ),
65 Error::InvalidPrefix { label } => write!(f, "Invalid {label} ciphertext prefix."),
66 Error::TooShort { label } => write!(f, "{label} ciphertext too short."),
67 Error::MacVerificationFailed { label } => write!(f, "{label} MAC verification failed."),
68 Error::DecryptionFailed { label } => write!(f, "{label} decryption failed."),
69 Error::EncryptionFailed { label } => write!(f, "{label} encryption failed."),
70 Error::UnknownIdentifier { kind, identifier } => {
71 write!(f, "Unknown {kind} identifier \"{identifier}\".")
72 }
73 Error::InvalidMasterKey { got } => {
74 write!(f, "Master key must be exactly 32 bytes (got {got}).")
75 }
76 Error::InvalidKey { label } => write!(f, "Invalid {label} key."),
77 Error::InvalidIterations => write!(f, "PBKDF2 iterations must be positive."),
78 Error::InvalidOutputLength { requested, max } => {
79 if *requested == 0 {
80 write!(f, "Output length must be positive.")
81 } else {
82 write!(f, "Output length {requested} exceeds the maximum of {max}.")
83 }
84 }
85 Error::InvalidHex => write!(f, "Invalid hex string."),
86 Error::UnsupportedNationalAlgorithm { name, hint } => {
87 write!(f, "{name} is not provided by this library: {hint}")
88 }
89 Error::MissingConfig { key } => {
90 write!(f, "Required configuration \"{key}\" was not found.")
91 }
92 }
93 }
94}
95
96impl std::error::Error for Error {}
97
98pub type Result<T> = std::result::Result<T, Error>;