1use crate::{Error, Result};
4use core::{
5 fmt::{self, Display},
6 str::FromStr,
7};
8
9#[cfg(feature = "password-hash")]
10use password_hash::Ident;
11
12#[cfg(feature = "password-hash")]
14#[cfg_attr(docsrs, doc(cfg(feature = "password-hash")))]
15pub const ARGON2D_IDENT: Ident<'_> = Ident::new_unwrap("argon2d");
16
17#[cfg(feature = "password-hash")]
19#[cfg_attr(docsrs, doc(cfg(feature = "password-hash")))]
20pub const ARGON2I_IDENT: Ident<'_> = Ident::new_unwrap("argon2i");
21
22#[cfg(feature = "password-hash")]
24#[cfg_attr(docsrs, doc(cfg(feature = "password-hash")))]
25pub const ARGON2ID_IDENT: Ident<'_> = Ident::new_unwrap("argon2id");
26
27#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Default, Ord)]
29pub enum Algorithm {
30 Argon2d = 0,
35
36 Argon2i = 1,
41
42 #[default]
51 Argon2id = 2,
52}
53
54impl Algorithm {
55 pub fn new(id: impl AsRef<str>) -> Result<Self> {
57 id.as_ref().parse()
58 }
59
60 pub const fn as_str(&self) -> &'static str {
62 match self {
63 Algorithm::Argon2d => "argon2d",
64 Algorithm::Argon2i => "argon2i",
65 Algorithm::Argon2id => "argon2id",
66 }
67 }
68
69 #[cfg(feature = "password-hash")]
71 #[cfg_attr(docsrs, doc(cfg(feature = "password-hash")))]
72 pub const fn ident(&self) -> Ident<'static> {
73 match self {
74 Algorithm::Argon2d => ARGON2D_IDENT,
75 Algorithm::Argon2i => ARGON2I_IDENT,
76 Algorithm::Argon2id => ARGON2ID_IDENT,
77 }
78 }
79
80 pub(crate) const fn to_le_bytes(self) -> [u8; 4] {
82 (self as u32).to_le_bytes()
83 }
84}
85
86impl AsRef<str> for Algorithm {
87 fn as_ref(&self) -> &str {
88 self.as_str()
89 }
90}
91
92impl Display for Algorithm {
93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 f.write_str(self.as_str())
95 }
96}
97
98impl FromStr for Algorithm {
99 type Err = Error;
100
101 fn from_str(s: &str) -> Result<Algorithm> {
102 match s {
103 "argon2d" => Ok(Algorithm::Argon2d),
104 "argon2i" => Ok(Algorithm::Argon2i),
105 "argon2id" => Ok(Algorithm::Argon2id),
106 _ => Err(Error::AlgorithmInvalid),
107 }
108 }
109}
110
111#[cfg(feature = "password-hash")]
112#[cfg_attr(docsrs, doc(cfg(feature = "password-hash")))]
113impl From<Algorithm> for Ident<'static> {
114 fn from(alg: Algorithm) -> Ident<'static> {
115 alg.ident()
116 }
117}
118
119#[cfg(feature = "password-hash")]
120#[cfg_attr(docsrs, doc(cfg(feature = "password-hash")))]
121impl<'a> TryFrom<Ident<'a>> for Algorithm {
122 type Error = password_hash::Error;
123
124 fn try_from(ident: Ident<'a>) -> password_hash::Result<Algorithm> {
125 match ident {
126 ARGON2D_IDENT => Ok(Algorithm::Argon2d),
127 ARGON2I_IDENT => Ok(Algorithm::Argon2i),
128 ARGON2ID_IDENT => Ok(Algorithm::Argon2id),
129 _ => Err(password_hash::Error::Algorithm),
130 }
131 }
132}