-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathiter.rs
More file actions
164 lines (138 loc) · 5.26 KB
/
iter.rs
File metadata and controls
164 lines (138 loc) · 5.26 KB
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
use std::ops::{Range, RangeInclusive};
use anyhow::format_err;
use proc_macro2::{Literal, TokenStream};
use quote::quote;
use crate::attr::{Discriminant, Enum, ErrorList};
enum IterImpl {
Empty,
Range {
repr: syn::Path,
range: Range<Discriminant>,
},
RangeInclusive {
repr: syn::Path,
range: RangeInclusive<Discriminant>,
},
Slice(Vec<TokenStream>),
}
impl IterImpl {
/// Constructs the fastest `IterImpl` for the given set of discriminants.
///
/// If the discriminants form a single, contiguous, increasing run, we will create a
/// `Range` (or `RangeInclusive`) containing the discriminants as the `#[repr(...)]` of the
/// enum.
fn for_enum(Enum { name, variants, discriminants, primitive_repr, .. }: &Enum) -> Result<Self, ErrorList> {
// See if we can generate a fast, transmute-based iterator.
if let Some(discriminants) = discriminants {
let is_zst = discriminants.len() <= 1;
if let Ok(Some((repr, repr_path))) = primitive_repr {
let unskipped_discriminants: Vec<_> = discriminants
.iter()
.cloned()
.zip(variants.iter())
.filter(|(_, (_, attr))| !attr.skip)
.map(|(d, _)| d)
.collect();
if unskipped_discriminants.is_empty() {
return Ok(IterImpl::Empty);
}
if !is_zst {
if let Some(range) = detect_contiguous_run(unskipped_discriminants.into_iter()) {
// If range.end() is less than the maximum value of the primitive repr, we can
// use the (faster) non-inclusive `Range`
let end = *range.end();
if end < 0 || repr.max_value().map_or(false, |max| (end as u128) < max) {
return Ok(IterImpl::Range {
repr: repr_path.clone(),
range: *range.start()..(end + 1),
})
}
return Ok(IterImpl::RangeInclusive {
repr: repr_path.clone(),
range,
})
}
}
}
}
// ...if not, fall back to the slice based one.
let mut errors = ErrorList::new();
let unskipped_variants: Vec<_> = variants
.iter()
.filter_map(|(v, attr)| {
if attr.skip {
return None;
}
if v.fields != syn::Fields::Unit {
errors.push_back(format_err!("An (unskipped) variant cannot have fields"));
return None;
}
let vident = &v.ident;
Some(quote!(#name::#vident))
})
.collect();
if !errors.is_empty() {
return Err(errors);
}
if unskipped_variants.is_empty() {
return Ok(IterImpl::Empty);
}
Ok(IterImpl::Slice(unskipped_variants))
}
fn tokens(&self, ty: &syn::Ident) -> TokenStream {
let body = match self {
IterImpl::Empty => quote! {
::std::iter::empty()
},
IterImpl::Range { range, repr } => {
let start = Literal::i128_unsuffixed(range.start);
let end = Literal::i128_unsuffixed(range.end);
quote! {
let start: #repr = #start;
let end: #repr = #end;
(start .. end).map(|discrim| unsafe { ::std::mem::transmute(discrim) })
}
},
IterImpl::RangeInclusive { range, repr } => {
let start = Literal::i128_unsuffixed(*range.start());
let end = Literal::i128_unsuffixed(*range.end());
quote! {
let start: #repr = #start;
let end: #repr = #end;
(start ..= end).map(|discrim| unsafe { ::std::mem::transmute(discrim) })
}
},
IterImpl::Slice(variants) => quote! {
const VARIANTS: &[#ty] = &[#( #variants ),*];
VARIANTS.iter().cloned()
},
};
quote! {
impl #ty {
fn iter() -> impl Iterator<Item = #ty> + Clone {
#body
}
}
}
}
}
/// Returns a range containing the discriminants of this enum if they comprise a single, contiguous
/// run. Returns `None` if there were no discriminants or they were not contiguous.
fn detect_contiguous_run(mut discriminants: impl Iterator<Item = Discriminant>)
-> Option<RangeInclusive<Discriminant>>
{
let first = discriminants.next()?;
let mut last = first;
while let Some(next) = discriminants.next() {
if last.checked_add(1)? != next {
return None;
}
last = next
}
Some(first..=last)
}
pub fn derive(input: &syn::DeriveInput) -> Result<TokenStream, ErrorList> {
let input = Enum::parse(input)?;
let imp = IterImpl::for_enum(&input)?;
Ok(imp.tokens(&input.name))
}