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
use std::str::FromStr;
use proc_macro2::{TokenStream, Span};
use syn::{
spanned::Spanned,
Meta, NestedMeta, Lit, Attribute, Variant, Field,
};
fn find_meta_item<'a, F, R, I>(itr: I, pred: F) -> Option<R> where
F: FnMut(&NestedMeta) -> Option<R> + Clone,
I: Iterator<Item=&'a Attribute>
{
itr.filter_map(|attr| {
if attr.path.is_ident("codec") {
if let Ok(Meta::List(ref meta_list)) = attr.parse_meta() {
return meta_list.nested.iter().filter_map(pred.clone()).next();
}
}
None
}).next()
}
pub fn index(v: &Variant, i: usize) -> TokenStream {
let index = find_meta_item(v.attrs.iter(), |meta| {
if let NestedMeta::Meta(Meta::NameValue(ref nv)) = meta {
if nv.path.is_ident("index") {
if let Lit::Str(ref s) = nv.lit {
let byte: u8 = s.value().parse().expect("Numeric index expected.");
return Some(byte)
}
}
}
None
});
index.map(|i| quote! { #i })
.unwrap_or_else(|| v.discriminant
.as_ref()
.map(|&(_, ref expr)| quote! { #expr })
.unwrap_or_else(|| quote! { #i })
)
}
pub fn get_encoded_as_type(field_entry: &Field) -> Option<TokenStream> {
find_meta_item(field_entry.attrs.iter(), |meta| {
if let NestedMeta::Meta(Meta::NameValue(ref nv)) = meta {
if nv.path.is_ident("encoded_as") {
if let Lit::Str(ref s) = nv.lit {
return Some(
TokenStream::from_str(&s.value())
.expect("`encoded_as` should be a valid rust type!")
);
}
}
}
None
})
}
pub fn get_enable_compact(field_entry: &Field) -> bool {
find_meta_item(field_entry.attrs.iter(), |meta| {
if let NestedMeta::Meta(Meta::Path(ref path)) = meta {
if path.is_ident("compact") {
return Some(());
}
}
None
}).is_some()
}
pub fn get_skip(attrs: &[Attribute]) -> Option<Span> {
find_meta_item(attrs.iter(), |meta| {
if let NestedMeta::Meta(Meta::Path(ref path)) = meta {
if path.is_ident("skip") {
return Some(path.span());
}
}
None
})
}
pub fn get_dumb_trait_bound(attrs: &[Attribute]) -> bool {
find_meta_item(attrs.iter(), |meta| {
if let NestedMeta::Meta(Meta::Path(ref path)) = meta {
if path.is_ident("dumb_trait_bound") {
return Some(());
}
}
None
}).is_some()
}
pub fn filter_skip_named<'a>(fields: &'a syn::FieldsNamed) -> impl Iterator<Item=&Field> + 'a {
fields.named.iter()
.filter(|f| get_skip(&f.attrs).is_none())
}
pub fn filter_skip_unnamed<'a>(fields: &'a syn::FieldsUnnamed) -> impl Iterator<Item=(usize, &Field)> + 'a {
fields.unnamed.iter()
.enumerate()
.filter(|(_, f)| get_skip(&f.attrs).is_none())
}