bcrypt/
errors.rs

1use core::fmt;
2
3#[cfg(feature = "std")]
4use std::error;
5
6/// Library generic result type.
7pub type BcryptResult<T> = Result<T, BcryptError>;
8
9#[derive(Debug)]
10/// All the errors we can encounter while hashing/verifying
11/// passwords
12pub 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
29macro_rules! impl_from_error {
30    ($f: ty, $e: expr) => {
31        impl From<$f> for BcryptError {
32            fn from(f: $f) -> BcryptError {
33                $e(f)
34            }
35        }
36    };
37}
38
39#[cfg(any(feature = "alloc", feature = "std"))]
40impl_from_error!(getrandom::Error, BcryptError::Rand);
41
42impl fmt::Display for BcryptError {
43    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
44        match *self {
45            BcryptError::CostNotAllowed(ref cost) => write!(
46                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            BcryptError::InvalidHash(ref reason) => write!(f, "Invalid hash: {}", reason),
54            #[cfg(any(feature = "alloc", feature = "std"))]
55            BcryptError::Rand(ref err) => write!(f, "Rand error: {}", err),
56            BcryptError::Truncation(len) => {
57                write!(f, "Expected 72 bytes or fewer; found {len} bytes")
58            }
59        }
60    }
61}
62
63#[cfg(feature = "std")]
64impl error::Error for BcryptError {
65    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
66        match *self {
67            BcryptError::CostNotAllowed(_)
68            | BcryptError::InvalidHash(_)
69            | BcryptError::Truncation(_) => None,
70            BcryptError::Rand(ref err) => Some(err),
71        }
72    }
73}