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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
mod phone_attribute;
use std::str::FromStr;
use phone_attribute::PhoneAttribute;
use quote::quote;
use syn::{Data, DeriveInput, Fields, Meta, Path};
use super::ValidatorHandler;
use crate::{common::type_enum::TypeEnum, panic};
pub(crate) struct PhoneHandler;
#[allow(dead_code)]
#[derive(Debug)]
pub struct Struct(TypeEnum);
const ITEM: Struct = Struct(TypeEnum::String);
const ITEM_MAP: Struct = Struct(TypeEnum::HashMapPhoneNumber);
impl ValidatorHandler for PhoneHandler {
fn meta_handler(ast: DeriveInput, meta: Meta) -> syn::Result<proc_macro2::TokenStream> {
let type_attribute = PhoneAttribute::build_from_meta(&meta)?;
if let Data::Struct(data) = ast.data
&& let Fields::Unnamed(_) = &data.fields
&& data.fields.len() == 1
{
let mut token_stream = proc_macro2::TokenStream::new();
let name = ast.ident;
let error_path: Path = syn::parse2(quote! { validators_prelude::PhoneError }).unwrap();
#[cfg(feature = "test")]
{
let c: Vec<proc_macro2::TokenStream> = type_attribute
.countries
.iter()
.map(|id| proc_macro2::TokenStream::from_str(id.as_ref()).unwrap())
.collect();
let size = c.len();
token_stream.extend(quote! {
impl #name {
pub(crate) const V_COUNTRIES: [validators_prelude::phonenumber::country::Id; #size] = [#(validators_prelude::phonenumber::country::Id::#c, )*];
}
});
}
token_stream.extend(match type_attribute.countries.len() {
0 => {
quote! {
impl #name {
#[inline]
fn v_parse_str(s: &str) -> Result<validators_prelude::phonenumber::PhoneNumber, #error_path> {
let phonenumber = validators_prelude::phonenumber::parse(None, s)?;
if phonenumber.is_valid() {
Ok(phonenumber)
} else {
Err(#error_path::Invalid)
}
}
}
}
},
1 => {
let c = proc_macro2::TokenStream::from_str(type_attribute.countries.iter().next().unwrap().as_ref())
.unwrap();
quote! {
impl #name {
#[inline]
fn v_parse_str(s: &str) -> Result<validators_prelude::phonenumber::PhoneNumber, #error_path> {
let phonenumber = validators_prelude::phonenumber::parse(Some(validators_prelude::phonenumber::country::Id::#c), s)?;
if let Some(id) = phonenumber.country().id() {
if id == validators_prelude::phonenumber::country::Id::#c && phonenumber.is_valid() {
Ok(phonenumber)
} else {
Err(#error_path::Invalid)
}
} else {
Err(#error_path::Invalid)
}
}
}
}
},
_ => {
let c: Vec<proc_macro2::TokenStream> = type_attribute.countries
.iter()
.map(|id| proc_macro2::TokenStream::from_str(id.as_ref()).unwrap())
.collect();
quote! {
impl #name {
#[inline]
fn v_parse_str(s: &str) -> Result<::std::collections::HashMap<validators_prelude::phonenumber::country::Id, validators_prelude::phonenumber::PhoneNumber>, #error_path> {
let mut map = ::std::collections::HashMap::with_capacity(2);
#(
let phonenumber = validators_prelude::phonenumber::parse(Some(validators_prelude::phonenumber::country::Id::#c), s)?;
if let Some(id) = phonenumber.country().id() {
if id == validators_prelude::phonenumber::country::Id::#c && phonenumber.is_valid() {
map.insert(validators_prelude::phonenumber::country::Id::#c, phonenumber);
}
}
)*
if map.is_empty() {
Err(#error_path::Invalid)
} else {
Ok(map)
}
}
}
}
}
});
token_stream.extend(quote! {
impl ValidateString for #name {
type Error = #error_path;
#[inline]
fn parse_string<S: Into<validators_prelude::String>>(s: S) -> Result<Self, Self::Error> {
Ok(Self(Self::v_parse_str(s.into().as_str())?))
}
#[inline]
fn parse_str<S: AsRef<str>>(s: S) -> Result<Self, Self::Error> {
Ok(Self(Self::v_parse_str(s.as_ref())?))
}
#[inline]
fn validate_str<S: AsRef<str>>(s: S) -> Result<(), Self::Error> {
Self::v_parse_str(s.as_ref())?;
Ok(())
}
}
});
#[cfg(feature = "serde")]
{
if type_attribute.serde_options.serialize {
token_stream.extend(quote! {
impl validators_prelude::serde::Serialize for #name {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: validators_prelude::serde::Serializer, {
validators_prelude::serde::Serialize::serialize(&self.0, serializer)
}
}
});
}
if type_attribute.serde_options.deserialize {
use std::fmt::Write;
let expect = {
let mut s = String::new();
if type_attribute.countries.is_empty() {
s.push_str("an international phone number");
} else {
s.push_str("a phone number in ");
s.write_fmt(format_args!("{:?}", type_attribute.countries)).unwrap();
}
s
};
token_stream.extend(quote! {
impl<'de> validators_prelude::serde::Deserialize<'de> for #name {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: validators_prelude::serde::Deserializer<'de>, {
struct MyVisitor;
impl<'de> validators_prelude::serde::de::Visitor<'de> for MyVisitor {
type Value = #name;
#[inline]
fn expecting(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
f.write_str(#expect)
}
#[inline]
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: validators_prelude::serde::de::Error, {
<#name as ValidateString>::parse_str(v).map_err(validators_prelude::serde::de::Error::custom)
}
}
deserializer.deserialize_str(MyVisitor)
}
}
});
}
}
#[cfg(feature = "rocket")]
{
if type_attribute.rocket_options.from_form_field {
crate::common::rocket::impl_from_form_field(&mut token_stream, &name);
}
if type_attribute.rocket_options.from_param {
crate::common::rocket::impl_from_param(&mut token_stream, &name, &error_path);
}
}
return Ok(token_stream);
}
if type_attribute.countries.len() > 1 {
Err(panic::validator_for_specific_item(meta.path(), ITEM_MAP))
} else {
Err(panic::validator_for_specific_item(meta.path(), ITEM))
}
}
}