use core::fmt;
pub type BcryptResult<T> = Result<T, BcryptError>;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum BcryptError {
CostNotAllowed(u32),
InvalidHash(&'static str),
Truncation(usize),
Rand(EntropyError),
BatchLengthMismatch {
passwords: usize,
salts: usize,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EntropyError {
code: Option<i32>,
}
impl EntropyError {
#[cfg_attr(not(feature = "std"), allow(dead_code))]
pub(crate) const fn new(code: Option<i32>) -> Self {
EntropyError { code }
}
#[inline]
#[must_use]
pub const fn code(self) -> Option<i32> {
self.code
}
}
impl fmt::Display for EntropyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.code {
Some(code) => write!(f, "OS entropy source failed (code {code})"),
None => f.write_str("OS entropy source failed"),
}
}
}
impl fmt::Display for BcryptError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
BcryptError::CostNotAllowed(cost) => {
write!(f, "cost {cost} not allowed: must be in 4..=31")
}
BcryptError::InvalidHash(part) => write!(f, "invalid hash: {part}"),
BcryptError::Truncation(len) => {
write!(f, "password is {len} bytes; bcrypt truncates at 72")
}
BcryptError::Rand(err) => write!(f, "{err}"),
BcryptError::BatchLengthMismatch { passwords, salts } => {
write!(
f,
"batch length mismatch: {passwords} passwords but {salts} salts"
)
}
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for EntropyError {}
#[cfg(feature = "std")]
impl std::error::Error for BcryptError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
BcryptError::Rand(err) => Some(err),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::string::ToString;
#[test]
fn display_is_informative() {
assert_eq!(
BcryptError::CostNotAllowed(3).to_string(),
"cost 3 not allowed: must be in 4..=31"
);
assert!(BcryptError::Truncation(73).to_string().contains("72"));
assert_eq!(
BcryptError::BatchLengthMismatch {
passwords: 3,
salts: 2
}
.to_string(),
"batch length mismatch: 3 passwords but 2 salts"
);
assert_eq!(EntropyError::new(Some(1)).code(), Some(1));
assert!(EntropyError::new(None).to_string().contains("failed"));
}
}