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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
use std::fmt;
use std::ops::Deref;
use std::{ops::Range, str::FromStr};
use serde::de::Visitor;
use serde::{Deserialize, Serialize};
use crate::util::{id_from_hashed_string, id_from_uuid};
pub const SEPERATOR: &str = "_";
#[derive(Debug, Default, PartialEq, Clone)]
pub struct GuidParseError;
impl std::error::Error for GuidParseError {}
impl fmt::Display for GuidParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Failed to parse GUID")
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Guid {
guid: String,
typ: Range<usize>,
id: Range<usize>,
}
impl fmt::Display for Guid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.guid)
}
}
impl Serialize for Guid {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&self.guid)
}
}
impl<'de> Deserialize<'de> for Guid {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct GuidVisitor;
impl<'de> Visitor<'de> for GuidVisitor {
type Value = Guid;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a valid GUID string in the form \"typ_id\"")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Guid::from_str(v).map_err(|e| E::custom(format!("{}", e)))
}
}
deserializer.deserialize_str(GuidVisitor)
}
}
impl Guid {
pub fn guid(&self) -> &str {
&self.guid
}
pub fn typ(&self) -> &str {
&self.guid[self.typ.start..self.typ.end]
}
pub fn id(&self) -> &str {
&self.guid[self.id.start..self.id.end]
}
pub fn from_parts(typ: &str, id: &str) -> Self {
let guid = format!("{}{}{}", typ, SEPERATOR, id);
Self {
typ: 0..typ.len(),
id: (typ.len() + SEPERATOR.len())..guid.len(),
guid,
}
}
pub fn into_parts(self) -> (String, String) {
(self.typ().to_string(), self.id().to_string())
}
pub fn into_guid(self) -> String {
self.guid
}
pub fn with_typ_and_random(typ: &str) -> Self {
Self::from_parts(typ, &id_from_uuid())
}
pub fn with_typ_and_seed(typ: &str, seed: &str) -> Self {
Self::from_parts(typ, &id_from_hashed_string(seed))
}
}
impl Deref for Guid {
type Target = str;
fn deref(&self) -> &Self::Target {
&self.guid
}
}
impl FromStr for Guid {
type Err = GuidParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.starts_with(SEPERATOR) || s.ends_with(SEPERATOR) {
return Err(GuidParseError);
}
let parts: Vec<&str> = s.split_terminator(SEPERATOR).collect();
match parts.as_slice() {
[typ, id] if !typ.is_empty() && !id.is_empty() => Ok(Self {
guid: s.to_string(),
typ: 0..typ.len(),
id: (typ.len() + SEPERATOR.len())..s.len(),
}),
_ => Err(GuidParseError),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn guid() {
let guid = Guid::from_parts("foo", "bar");
assert_eq!(guid.guid(), "foo_bar");
assert_eq!(&*guid, "foo_bar");
assert_eq!(guid.typ(), "foo");
assert_eq!(guid.id(), "bar");
}
#[test]
fn parse_guid() {
let s = "oas.Media_pic1312";
let guid = Guid::from_str(s).expect("failed to parse uid");
assert_eq!(guid.typ(), "oas.Media");
assert_eq!(guid.id(), "pic1312");
let invalid = [
"_",
"__",
"_foo",
"foo_",
"foo_bar_",
"foo_bar_boo",
"_foo_bar",
"foo_bar_",
];
for s in invalid.iter() {
assert_eq!(
Guid::from_str(s).err(),
Some(GuidParseError),
"invalid guid: {} (got: {:?})",
s,
Guid::from_str(s)
);
}
}
#[test]
fn serde() {
use serde::{Deserialize, Serialize};
let src = r#"{ "guid": "foo_bar" }"#;
#[derive(Serialize, Deserialize, Debug)]
struct Data {
guid: Guid,
}
let x: Data = serde_json::from_str(src).expect("failed to deserialize");
assert_eq!(x.guid.typ(), "foo");
assert_eq!(x.guid.id(), "bar");
let ser = serde_json::to_string(&x).expect("failed to serialize");
assert_eq!(ser, fmtjson(src), "json does not match");
}
fn fmtjson(json: &str) -> String {
serde_json::to_string(
&serde_json::from_str::<serde_json::Value>(json).expect("failed to parse"),
)
.expect("failed to serialize")
}
}