bcrypt_no_getrandom/
errors.rs1use core::fmt;
2
3#[cfg(feature = "std")]
4use std::error;
5#[cfg(feature = "std")]
6use std::io;
7
8pub type BcryptResult<T> = Result<T, BcryptError>;
10
11#[derive(Debug)]
12pub enum BcryptError {
15 #[cfg(feature = "std")]
16 Io(io::Error),
17 CostNotAllowed(u32),
18 InvalidCost,
19 InvalidPrefix,
20 InvalidHash(&'static str),
21 InvalidSaltLen(usize),
22 InvalidSalt,
23 InvalidBase64(base64::DecodeSliceError),
24 Other(&'static str),
25}
26
27macro_rules! impl_from_error {
28 ($f: ty, $e: expr) => {
29 impl From<$f> for BcryptError {
30 fn from(f: $f) -> BcryptError {
31 $e(f)
32 }
33 }
34 };
35}
36
37impl_from_error!(base64::DecodeSliceError, BcryptError::InvalidBase64);
38#[cfg(feature = "std")]
39impl_from_error!(io::Error, BcryptError::Io);
40
41impl fmt::Display for BcryptError {
42 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
43 match *self {
44 #[cfg(feature = "std")]
45 BcryptError::Io(ref err) => write!(f, "IO error: {}", err),
46 BcryptError::InvalidCost => write!(f, "Invalid Cost"),
47 BcryptError::CostNotAllowed(ref cost) => write!(
48 f,
49 "Cost needs to be between {} and {}, got {}",
50 crate::MIN_COST,
51 crate::MAX_COST,
52 cost
53 ),
54 BcryptError::InvalidPrefix => write!(f, "Invalid Prefix"),
55 BcryptError::InvalidHash(ref hash) => write!(f, "Invalid hash: {}", hash),
56 BcryptError::InvalidBase64(ref err) => write!(f, "Base64 error: {}", err),
57 BcryptError::InvalidSaltLen(len) => {
58 write!(f, "Invalid salt len: expected 16, received {}", len)
59 }
60 BcryptError::InvalidSalt => write!(f, "Invalid salt"),
61 BcryptError::Other(ref err) => write!(f, "{}", err),
62 }
63 }
64}
65
66#[cfg(feature = "std")]
67impl error::Error for BcryptError {
68 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
69 match *self {
70 BcryptError::Io(ref err) => Some(err),
71 BcryptError::InvalidCost
72 | BcryptError::InvalidSalt
73 | BcryptError::InvalidPrefix
74 | BcryptError::CostNotAllowed(_)
75 | BcryptError::InvalidHash(_)
76 | BcryptError::Other(_)
77 | BcryptError::InvalidSaltLen(_) => None,
78 BcryptError::InvalidBase64(ref err) => Some(err),
79 }
80 }
81}