use crate::utils::crypt_utils::sha256_str;
use std::fmt::Display;
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
#[serde(tag = "t")]
pub enum Nonce {
Hashed { id: uuid::Uuid },
Plain { val: String },
}
impl Default for Nonce {
fn default() -> Self {
Self::new()
}
}
impl Nonce {
pub fn new() -> Self {
Self::Hashed {
id: uuid::Uuid::new_v4(),
}
}
pub fn new_plain(d: impl Display) -> Self {
Self::Plain { val: d.to_string() }
}
pub fn hash(&self) -> String {
match self {
Nonce::Hashed { id } => {
let hash = sha256_str(id.as_bytes());
hash[0..hash.len() / 2].to_string()
}
Nonce::Plain { val } => val.to_string(),
}
}
}
#[cfg(test)]
mod tests {
use crate::nonce::Nonce;
#[test]
fn serialize_nonce() {
let nonce = Nonce::new();
let serialized = serde_json::to_string(&nonce).unwrap();
let deserialized: Nonce = serde_json::from_str(&serialized).unwrap();
assert_eq!(deserialized, nonce);
}
}