1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use std::{
convert::{TryFrom, TryInto},
fmt,
iter::repeat_with,
str::FromStr,
time::{SystemTime, UNIX_EPOCH},
};
#[derive(Clone, Debug, PartialEq, Hash)]
pub struct Guid(String);
impl Guid {
pub fn generate() -> Self {
let r: Vec<u32> = repeat_with(rand::random::<u32>).take(3).collect();
let r3 = match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(n) => n.as_secs() as u32,
Err(_) => rand::random::<u32>(),
};
let s = format!("{:08x}{:08x}{:08x}{:08x}", r[0], r[1], r[2], r3);
Self(s)
}
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
impl fmt::Display for Guid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl TryFrom<&str> for Guid {
type Error = crate::Error;
fn try_from(value: &str) -> std::result::Result<Self, Self::Error> {
if value.as_bytes().len() != 32 || !value.chars().all(|c| char::is_ascii_hexdigit(&c)) {
Err(crate::Error::InvalidGUID)
} else {
Ok(Guid(value.to_string()))
}
}
}
impl FromStr for Guid {
type Err = crate::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
s.try_into()
}
}
#[cfg(test)]
mod tests {
use crate::Guid;
#[test]
fn generate() {
let u1 = Guid::generate();
let u2 = Guid::generate();
assert_eq!(u1.as_str().len(), 32);
assert_eq!(u2.as_str().len(), 32);
assert_ne!(u1, u2);
assert_ne!(u1.as_str(), u2.as_str());
}
}