1use std::error;
2use std::fmt;
3use std::io;
4
5pub type BcryptResult<T> = Result<T, BcryptError>;
7
8#[derive(Debug)]
9pub enum BcryptError {
12 Io(io::Error),
13 CostNotAllowed(u32),
14 InvalidPassword,
15 InvalidCost(String),
16 InvalidPrefix(String),
17 InvalidHash(String),
18 InvalidBase64(char, String),
19 Rand(rand::Error),
20}
21
22macro_rules! impl_from_error {
23 ($f: ty, $e: expr) => {
24 impl From<$f> for BcryptError {
25 fn from(f: $f) -> BcryptError {
26 $e(f)
27 }
28 }
29 };
30}
31
32impl_from_error!(io::Error, BcryptError::Io);
33impl_from_error!(rand::Error, BcryptError::Rand);
34
35impl fmt::Display for BcryptError {
36 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
37 match *self {
38 BcryptError::Io(ref err) => write!(f, "IO error: {}", err),
39 BcryptError::InvalidCost(ref cost) => write!(f, "Invalid Cost: {}", cost),
40 BcryptError::CostNotAllowed(ref cost) => write!(
41 f,
42 "Cost needs to be between {} and {}, got {}",
43 crate::MIN_COST,
44 crate::MAX_COST,
45 cost
46 ),
47 BcryptError::InvalidPassword => write!(f, "Invalid password: contains NULL byte"),
48 BcryptError::InvalidPrefix(ref prefix) => write!(f, "Invalid Prefix: {}", prefix),
49 BcryptError::InvalidHash(ref hash) => write!(f, "Invalid hash: {}", hash),
50 BcryptError::InvalidBase64(ref c, ref hash) => {
51 write!(f, "Invalid base64 char {} in {}", c, hash)
52 }
53 BcryptError::Rand(ref err) => write!(f, "Rand error: {}", err),
54 }
55 }
56}
57
58impl error::Error for BcryptError {
59 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
60 match *self {
61 BcryptError::Io(ref err) => Some(err),
62 BcryptError::InvalidCost(_)
63 | BcryptError::CostNotAllowed(_)
64 | BcryptError::InvalidPassword
65 | BcryptError::InvalidPrefix(_)
66 | BcryptError::InvalidBase64(_, _)
67 | BcryptError::InvalidHash(_) => None,
68 BcryptError::Rand(ref err) => Some(err),
69 }
70 }
71}