1use core::fmt;
2
3#[cfg(feature = "std")]
4use std::error;
5
6pub type BcryptResult<T> = Result<T, BcryptError>;
8
9#[derive(Debug)]
10pub enum BcryptError {
13 CostNotAllowed(u32),
18 #[cfg(any(feature = "alloc", feature = "std"))]
20 InvalidHash(&'static str),
21 #[cfg(any(feature = "alloc", feature = "std"))]
23 Rand(getrandom::Error),
24 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}