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
use std::{
cmp, error, fmt,
marker::PhantomData,
str::{self, FromStr as _},
};
use serde::{
de::{self, SeqAccess, Visitor},
Deserialize, Deserializer, Serialize, Serializer,
};
pub const SCOPE_PARAMETER_DELIMITATION: char = ' ';
pub const SCOPE_OPENID: &str = "openid";
pub trait Scope: str::FromStr + ToString + fmt::Debug + Clone + cmp::PartialEq {}
impl Scope for String {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScopeParameter<T>(pub Vec<T>);
impl<T> From<Vec<T>> for ScopeParameter<T> {
fn from(v: Vec<T>) -> Self {
Self(v)
}
}
impl<T> str::FromStr for ScopeParameter<T>
where
T: Scope,
{
type Err = ScopeFromStrError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let split_char = if s.contains(SCOPE_PARAMETER_DELIMITATION) {
SCOPE_PARAMETER_DELIMITATION
} else if s.contains(',') {
','
} else {
SCOPE_PARAMETER_DELIMITATION
};
let mut inner = vec![];
for s in s.split(split_char) {
inner.push(T::from_str(s).map_err(|_| ScopeFromStrError::Unknown(s.to_owned()))?);
}
Ok(inner.into())
}
}
impl<T> Serialize for ScopeParameter<T>
where
T: Scope,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(
self.0
.iter()
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(SCOPE_PARAMETER_DELIMITATION.to_string().as_str())
.as_str(),
)
}
}
impl<'de, T> Deserialize<'de> for ScopeParameter<T>
where
T: Scope,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(ScopeParameterVisitor {
phantom: PhantomData,
})
}
}
struct ScopeParameterVisitor<T> {
phantom: PhantomData<T>,
}
impl<'de, T> Visitor<'de> for ScopeParameterVisitor<T>
where
T: Scope,
{
type Value = ScopeParameter<T>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("should be a str or seq")
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
ScopeParameter::<T>::from_str(s).map_err(de::Error::custom)
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let mut inner = vec![];
while let Some(s) = seq.next_element::<&str>()? {
inner.push(
T::from_str(s)
.map_err(|_| de::Error::custom(ScopeFromStrError::Unknown(s.to_owned())))?,
);
}
Ok(inner.into())
}
}
impl<T> From<&ScopeParameter<T>> for ScopeParameter<String>
where
T: Scope,
{
fn from(v: &ScopeParameter<T>) -> Self {
v.0.iter().map(|y| y.to_string()).collect::<Vec<_>>().into()
}
}
impl<T> ScopeParameter<T>
where
T: Scope,
{
pub fn try_from_t_with_string(v: &ScopeParameter<String>) -> Result<Self, ScopeFromStrError> {
let mut inner = vec![];
for s in v.0.iter() {
inner.push(T::from_str(s).map_err(|_| ScopeFromStrError::Unknown(s.to_owned()))?);
}
Ok(inner.into())
}
}
#[derive(Debug)]
pub enum ScopeFromStrError {
Unknown(String),
}
impl fmt::Display for ScopeFromStrError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl error::Error for ScopeFromStrError {}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Serialize, Deserialize)]
struct Foo {
scope: ScopeParameter<String>,
}
#[test]
fn de() {
match serde_json::from_str::<Foo>(r#"{"scope":"a b"}"#) {
Ok(v) => {
assert_eq!(v.scope, vec!["a".to_owned(), "b".to_owned()].into());
}
Err(err) => panic!("{}", err),
}
match serde_json::from_str::<Foo>(r#"{"scope":"a,b"}"#) {
Ok(v) => {
assert_eq!(v.scope, vec!["a".to_owned(), "b".to_owned()].into());
}
Err(err) => panic!("{}", err),
}
match serde_json::from_str::<Foo>(r#"{"scope":["a", "b"]}"#) {
Ok(v) => {
assert_eq!(v.scope, vec!["a".to_owned(), "b".to_owned()].into());
}
Err(err) => panic!("{}", err),
}
}
}