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