/rust/registry/src/index.crates.io-1949cf8c6b5b557f/bcrypt-0.18.0/src/errors.rs
Line | Count | Source |
1 | | use core::fmt; |
2 | | |
3 | | #[cfg(feature = "std")] |
4 | | use std::error; |
5 | | |
6 | | /// Library generic result type. |
7 | | pub type BcryptResult<T> = Result<T, BcryptError>; |
8 | | |
9 | | #[derive(Debug)] |
10 | | /// All the errors we can encounter while hashing/verifying |
11 | | /// passwords |
12 | | pub enum BcryptError { |
13 | | /// Raised when the cost value is outside of the allowed 4-31 range. |
14 | | /// |
15 | | /// Cost is provided as an argument to hashing functions, and extracted from the hash in |
16 | | /// verification functions. |
17 | | CostNotAllowed(u32), |
18 | | /// Raised when verifying against an incorrectly formatted hash. |
19 | | #[cfg(any(feature = "alloc", feature = "std"))] |
20 | | InvalidHash(&'static str), |
21 | | /// Raised when an error occurs when generating a salt value. |
22 | | #[cfg(any(feature = "alloc", feature = "std"))] |
23 | | Rand(getrandom::Error), |
24 | | /// Raised when the input to a `non_truncating_*` function contains more than 72 bytes. |
25 | | /// This variant contains the length of the input in bytes. |
26 | | Truncation(usize), |
27 | | } |
28 | | |
29 | | macro_rules! impl_from_error { |
30 | | ($f: ty, $e: expr) => { |
31 | | impl From<$f> for BcryptError { |
32 | 0 | fn from(f: $f) -> BcryptError { |
33 | 0 | $e(f) |
34 | 0 | } |
35 | | } |
36 | | }; |
37 | | } |
38 | | |
39 | | #[cfg(any(feature = "alloc", feature = "std"))] |
40 | | impl_from_error!(getrandom::Error, BcryptError::Rand); |
41 | | |
42 | | impl fmt::Display for BcryptError { |
43 | 0 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
44 | 0 | match *self { |
45 | 0 | BcryptError::CostNotAllowed(ref cost) => write!( |
46 | 0 | f, |
47 | | "Cost needs to be between {} and {}, got {}", |
48 | | crate::MIN_COST, |
49 | | crate::MAX_COST, |
50 | | cost |
51 | | ), |
52 | | #[cfg(any(feature = "alloc", feature = "std"))] |
53 | 0 | BcryptError::InvalidHash(ref reason) => write!(f, "Invalid hash: {}", reason), |
54 | | #[cfg(any(feature = "alloc", feature = "std"))] |
55 | 0 | BcryptError::Rand(ref err) => write!(f, "Rand error: {}", err), |
56 | 0 | BcryptError::Truncation(len) => { |
57 | 0 | write!(f, "Expected 72 bytes or fewer; found {len} bytes") |
58 | | } |
59 | | } |
60 | 0 | } |
61 | | } |
62 | | |
63 | | #[cfg(feature = "std")] |
64 | | impl error::Error for BcryptError { |
65 | 0 | fn source(&self) -> Option<&(dyn error::Error + 'static)> { |
66 | 0 | match *self { |
67 | | BcryptError::CostNotAllowed(_) |
68 | | | BcryptError::InvalidHash(_) |
69 | 0 | | BcryptError::Truncation(_) => None, |
70 | 0 | BcryptError::Rand(ref err) => Some(err), |
71 | | } |
72 | 0 | } |
73 | | } |