Skip to main content

password_auth/
errors.rs

1//! Error types.
2
3use alloc::string::ToString;
4use core::fmt;
5use password_hash::phc;
6
7/// Password hash parse errors.
8// This type has no public constructor and deliberately keeps `phc::Error` out of the public API
9// so we can upgrade the `phc` version without it being a breaking change
10#[derive(Clone, Copy, Eq, PartialEq)]
11pub struct ParseError(phc::Error);
12
13impl ParseError {
14    /// Create a new parse error.
15    pub(crate) fn new(err: phc::Error) -> Self {
16        Self(err)
17    }
18}
19
20impl fmt::Debug for ParseError {
21    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22        f.debug_tuple("ParseError")
23            .field(&self.0.to_string())
24            .finish()
25    }
26}
27
28impl fmt::Display for ParseError {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        write!(f, "{}", self.0)
31    }
32}
33
34impl core::error::Error for ParseError {
35    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
36        Some(&self.0)
37    }
38}
39
40/// Password verification errors.
41#[derive(Clone, Copy, Debug, Eq, PartialEq)]
42pub enum VerifyError {
43    /// Password hash parsing errors.
44    Parse(ParseError),
45
46    /// Password is invalid.
47    PasswordInvalid,
48}
49
50impl fmt::Display for VerifyError {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        match self {
53            Self::Parse(err) => write!(f, "{err}"),
54            Self::PasswordInvalid => write!(f, "password is invalid"),
55        }
56    }
57}
58
59impl From<ParseError> for VerifyError {
60    fn from(err: ParseError) -> VerifyError {
61        VerifyError::Parse(err)
62    }
63}
64
65impl core::error::Error for VerifyError {
66    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
67        match self {
68            Self::Parse(err) => Some(err),
69            _ => None,
70        }
71    }
72}