1use crate::crypto::{Digest, SecureRandom};
2pub use hex::FromHexError;
3use serde::{Deserialize, Serialize};
4use std::{convert::TryFrom, str::FromStr, string::ToString};
5
6#[derive(Default, Clone, Copy, Hash, PartialEq, Eq, Serialize, Deserialize)]
8pub struct Id(Digest);
9
10impl Id {
11 #[inline(always)]
12 pub fn new(random: &impl SecureRandom) -> Id {
13 let mut id = Id::default();
14 id.reset(random);
15 id
16 }
17
18 pub fn from_bytes(bytes: impl AsRef<[u8]>) -> Id {
19 let mut id = Id::default();
20 id.0.copy_from_slice(bytes.as_ref());
21
22 id
23 }
24
25 #[inline(always)]
26 pub fn reset(&mut self, random: &impl SecureRandom) {
27 random.fill(&mut self.0).unwrap();
28 }
29}
30
31impl AsRef<[u8]> for Id {
32 #[inline]
33 fn as_ref(&self) -> &[u8] {
34 &self.0
35 }
36}
37
38impl TryFrom<&str> for Id {
39 type Error = FromHexError;
40
41 fn try_from(value: &str) -> Result<Self, Self::Error> {
42 hex::decode(value).map(Self::from_bytes)
43 }
44}
45
46impl FromStr for Id {
47 type Err = FromHexError;
48
49 fn from_str(value: &str) -> Result<Self, <Self as FromStr>::Err> {
50 Self::try_from(value)
51 }
52}
53
54impl ToString for Id {
55 #[inline(always)]
56 fn to_string(&self) -> String {
57 hex::encode(self.0.as_ref())
58 }
59}
60
61impl std::fmt::Debug for Id {
62 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63 write!(f, "{}", self.to_string())
64 }
65}