1use std::{
6 error::Error,
7 fmt::{self, Display, Formatter},
8};
9
10#[derive(Debug)]
12pub enum CryptoError {
13 InternalError {
15 source: Box<dyn Error + Send + Sync>,
16 },
17
18 NotFound {
20 source: Box<dyn Error + Send + Sync>,
21 },
22
23 CiphertextFailedVerification,
25
26 InvalidKeyLength { expected: usize, actual: usize },
28
29 InvalidSeedLength { expected: usize, actual: usize },
31
32 NotDowncastable,
34
35 NotDeserializableToBaseDataType,
37
38 WrongNonceType,
40
41 BadSignature,
43}
44
45impl Error for CryptoError {
46 fn source(&self) -> Option<&(dyn Error + 'static)> {
47 match *self {
48 CryptoError::InternalError { ref source } => Some(source.as_ref()),
49 CryptoError::NotFound { ref source } => Some(source.as_ref()),
50 CryptoError::CiphertextFailedVerification => None,
51 CryptoError::InvalidKeyLength { .. } => None,
52 CryptoError::InvalidSeedLength { .. } => None,
53 CryptoError::NotDowncastable => None,
54 CryptoError::NotDeserializableToBaseDataType => None,
55 CryptoError::WrongNonceType => None,
56 CryptoError::BadSignature => None,
57 }
58 }
59}
60
61impl Display for CryptoError {
62 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
63 match *self {
64 CryptoError::InternalError { .. } => {
65 write!(f, "Internal error occurred")
66 }
67 CryptoError::NotFound { .. } => {
68 write!(f, "Requested resource not found")
69 }
70 CryptoError::CiphertextFailedVerification => {
71 write!(f, "Ciphertext failed verification before decryption")
72 }
73 CryptoError::InvalidKeyLength {
74 ref expected,
75 ref actual,
76 } => {
77 write!(
78 f,
79 "Provided key was not the correct length, expected: {}, actual: {}",
80 expected, actual,
81 )
82 }
83 CryptoError::InvalidSeedLength {
84 ref expected,
85 ref actual,
86 } => {
87 write!(
88 f,
89 "Provided seed was not the correct length, expected: {}, actual: {}",
90 expected, actual,
91 )
92 }
93 CryptoError::NotDowncastable => {
94 write!(
95 f,
96 "Could not downcast the Types-value into the requested variant"
97 )
98 }
99 CryptoError::NotDeserializableToBaseDataType => {
100 write!(f, "Given bytes could not be deserialized to one of: bool, u64, i64, f64, or string")
101 }
102 CryptoError::WrongNonceType => {
103 write!(f, "Invalid type of nonce was provided for the operation")
104 }
105 CryptoError::BadSignature => {
106 write!(f, "Signature verification failed")
107 }
108 }
109 }
110}
111
112#[cfg(test)]
113mod tests {
114 use super::CryptoError;
115
116 #[test]
117 fn test_to_string_internal_error() {
118 let s = CryptoError::InternalError {
119 source: Box::new(CryptoError::NotDowncastable),
120 }
121 .to_string();
122 assert_eq!(s, "Internal error occurred");
123 }
124
125 #[test]
126 fn test_to_string_not_found() {
127 let s = CryptoError::NotDowncastable.to_string();
128 assert_eq!(
129 s,
130 "Could not downcast the Types-value into the requested variant"
131 );
132 }
133}