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
use std::hash::Hash;
use std::str::FromStr;
use std::sync::Arc;
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use crate::error::ErrorKind;
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
pub struct Identifier(Arc<str>);
impl Identifier {
pub fn new(s: impl Into<Arc<str>>) -> Result<Self, ErrorKind> {
let string = s.into();
if is_valid_identifier(&string) {
Ok(Identifier(string))
} else {
Err(ErrorKind::BadIdentifier)
}
}
pub fn from_uuidv4() -> Self {
Self::new(uuid::Uuid::new_v4().to_string()).unwrap()
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl PartialEq<String> for Identifier {
fn eq(&self, other: &String) -> bool {
*self.0 == *other
}
}
impl FromStr for Identifier {
type Err = ErrorKind;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Identifier::new(s)
}
}
fn is_valid_identifier(s: &Arc<str>) -> bool {
s.len() <= 100 && s.bytes().all(|b| (0x20..=0x7E).contains(&b))
}
impl Serialize for Identifier {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
debug_assert!(
is_valid_identifier(&self.0),
"all identifiers are validated on construction"
);
serializer.serialize_str(&self.0)
}
}
impl<'de> Deserialize<'de> for Identifier {
fn deserialize<D>(deserializer: D) -> Result<Identifier, D::Error>
where
D: Deserializer<'de>,
{
let string = String::deserialize(deserializer)?;
Identifier::new(string).map_err(|_| de::Error::custom("Identifier must be at most 100 characters long and contain only ASCII characters in the range 0x20 to 0x7E."))
}
}