1use crate::utils::crypt_utils::sha256_str;
2use std::fmt::Display;
3
4#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
6#[serde(tag = "t")]
7pub enum Nonce {
8 Hashed { id: uuid::Uuid },
9 Plain { val: String },
10}
11
12impl Default for Nonce {
13 fn default() -> Self {
14 Self::new()
15 }
16}
17
18impl Nonce {
19 pub fn new() -> Self {
21 Self::Hashed {
22 id: uuid::Uuid::new_v4(),
23 }
24 }
25
26 pub fn new_plain(d: impl Display) -> Self {
29 Self::Plain { val: d.to_string() }
30 }
31
32 pub fn hash(&self) -> String {
34 match self {
35 Nonce::Hashed { id } => {
36 let hash = sha256_str(id.as_bytes());
37 hash[0..hash.len() / 2].to_string()
38 }
39 Nonce::Plain { val } => val.to_string(),
40 }
41 }
42}
43
44#[cfg(test)]
45mod tests {
46 use crate::nonce::Nonce;
47
48 #[test]
49 fn serialize_nonce() {
50 let nonce = Nonce::new();
51 let serialized = serde_json::to_string(&nonce).unwrap();
52 let deserialized: Nonce = serde_json::from_str(&serialized).unwrap();
53 assert_eq!(deserialized, nonce);
54 }
55}