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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
|
#![feature(slice_patterns)]
#![doc(html_root_url = "https://docs.rs/improved_slice_patterns/2.0.0")]
//! A tiny crate that provides two macros to help matching
//! on `Vec`s and iterators using the syntax of
//! [`slice_patterns`][slice_patterns]
//!
//! [slice_patterns]: https://doc.rust-lang.org/nightly/unstable-book/language-features/slice-patterns.html
/// Destructure an iterator using the syntax of slice_patterns.
///
/// Wraps the match body in `Some` if there was a match; returns
/// `None` otherwise.
///
/// Contrary to slice_patterns, this allows moving out
/// of the iterator.
///
/// A variable length pattern (`x..`) is only allowed as the last
/// pattern, unless the iterator is double-ended.
///
/// Example:
/// ```edition2018
/// use improved_slice_patterns::destructure_iter;
///
/// let vec = vec![Some(1), Some(2), Some(3), None];
///
/// let res = destructure_iter!(vec.into_iter();
/// [Some(x), y.., z] => {
/// // x: usize
/// // y: impl Iterator<Option<usize>>
/// // z: Option<usize>
/// (x, y.collect::<Vec<_>>(), z)
/// }
/// );
///
/// assert_eq!(res, Some((1, vec![Some(2), Some(3)], None)));
///
/// # Ok::<(), ()>(())
/// ```
///
///
#[macro_export]
macro_rules! destructure_iter {
// Variable length pattern
(@match_forwards, $iter:expr, ($body:expr), $x:ident.., $($rest:tt)*) => {
$crate::destructure_iter!(@match_backwards,
$iter,
({
let $x = $iter;
$body
}),
$($rest)*
)
};
// Special variable length pattern with a common unary variant
(@match_forwards, $iter:expr, ($body:expr),
$variant:ident ($x:ident).., $($rest:tt)*) => {
$crate::destructure_iter!(@match_backwards,
$iter,
({
let $x = $iter
.map(|x| match x {
$variant(y) => y,
_ => unreachable!(),
});
$body
}),
$($rest)*
)
};
// Variable length pattern without a binder
(@match_forwards, $iter:expr, ($body:expr), .., $($rest:tt)*) => {
$crate::destructure_iter!(@match_backwards,
$iter,
($body),
$($rest)*
)
};
// Single item pattern
(@match_forwards, $iter:expr, ($body:expr), $x:pat, $($rest:tt)*) => {
if let std::option::Option::Some($x) = $iter.next() {
$crate::destructure_iter!(@match_forwards,
$iter,
($body),
$($rest)*
)
} else {
std::option::Option::None
}
};
// Single item pattern after a variable length one: declare reversed and take from the end
(@match_backwards, $iter:expr, ($body:expr), $x:pat, $($rest:tt)*) => {
$crate::destructure_iter!(@match_backwards, $iter, (
if let std::option::Option::Some($x) = $iter.next_back() {
$body
} else {
std::option::Option::None
}
), $($rest)*)
};
// Check no elements remain
(@match_forwards, $iter:expr, ($body:expr) $(,)*) => {
if $iter.next().is_some() {
std::option::Option::None
} else {
$body
}
};
// After a variable length pattern, everything has already been consumed
(@match_backwards, $iter:expr, ($body:expr) $(,)*) => {
$body
};
($iter:expr; [$($args:tt)*] => $body:expr) => {
{
#[allow(unused_mut)]
let mut iter = $iter;
$crate::destructure_iter!(@match_forwards,
iter,
(std::option::Option::Some($body)),
$($args)*,
)
}
};
}
/// Pattern-match on a vec using the syntax of slice_patterns.
///
/// Wraps the match body in `Ok` if there was a match; returns
/// an `Err` containing the ownership of the vec otherwise.
///
/// Contrary to slice_patterns, this allows moving out
/// of the `Vec`.
///
/// A variable length pattern (`x..`) returns an iterator.
///
/// Example:
/// ```edition2018
/// #![feature(slice_patterns)]
/// use improved_slice_patterns::match_vec;
///
/// let vec = vec![Some(1), Some(2), Some(3), None];
///
/// let res = match_vec!(vec;
/// [Some(_), y.., None] => {
/// y.collect::<Vec<_>>()
/// },
/// [None, None] => {
/// vec![]
/// },
/// [..] => vec![]
/// );
///
/// assert_eq!(res, Ok(vec![Some(2), Some(3)]));
///
///
/// let vec = vec![Some(1), Some(2), Some(3), None];
///
/// let res = match_vec!(vec;
/// [Some(_), y.., Some(_)] => {
/// y.collect::<Vec<_>>()
/// },
/// [None, None] => {
/// vec![]
/// },
/// );
///
/// assert!(res.is_err()); // there was no match
///
/// # Ok::<(), ()>(())
/// ```
///
///
#[macro_export]
macro_rules! match_vec {
// Variable length pattern
(@make_pat; ($($acc:tt)*), $x:ident.., $($rest:tt)*) => {
$crate::match_vec!(@make_pat;
($($acc)*, $x..),
$($rest)*
)
};
// Special variable length pattern with a common unary variant
(@make_pat; ($($acc:tt)*), $variant:ident ($x:ident).., $($rest:tt)*) => {
$crate::match_vec!(@make_pat;
($($acc)*, $x..),
$($rest)*
)
};
// Variable length pattern without a binder
(@make_pat; ($($acc:tt)*), .., $($rest:tt)*) => {
$crate::match_vec!(@make_pat;
($($acc)*, ..),
$($rest)*
)
};
// Single item pattern
(@make_pat; ($($acc:tt)*), $x:pat, $($rest:tt)*) => {
$crate::match_vec!(@make_pat;
($($acc)*, $x),
$($rest)*
)
};
(@make_pat; (, $($acc:tt)*), $(,)*) => {
[$($acc)*]
};
(@make_pat; ($($acc:tt)*), $(,)*) => {
[$($acc)*]
};
(@make_filter; $x:ident.., $($rest:tt)*) => {
$crate::match_vec!(@make_filter;
$($rest)*
)
};
(@make_filter; $variant:ident ($x:ident).., $($rest:tt)*) => {
{
// Circumvent https://github.com/rust-lang/rust/issues/59803
let is_all_variant = || $x.iter()
.all(|x| match x {
$variant(_) => true,
_ => false,
});
is_all_variant()
}
&&
$crate::match_vec!(@make_filter;
$($rest)*
)
};
(@make_filter; .., $($rest:tt)*) => {
$crate::match_vec!(@make_filter;
$($rest)*
)
};
(@make_filter; $x:pat, $($rest:tt)*) => {
$crate::match_vec!(@make_filter;
$($rest)*
)
};
(@make_filter; $(,)*) => {
true
};
($arg:expr; $( [$($args:tt)*] => $body:expr ),* $(,)*) => {
{
let vec = $arg;
// Match as references to decide which branch to take
// I think `match_default_bindings` should make this always work but
// there may be some patterns this doesn't capture.
#[allow(unused_variables, unreachable_patterns)]
match vec.as_slice() {
$(
$crate::match_vec!(@make_pat; (), $($args)*,)
if
$crate::match_vec!(@make_filter; $($args)*,)
=> {
// Actually consume the values
#[allow(unused_mut)]
let mut iter = vec.into_iter();
let ret =
$crate::destructure_iter!(iter;
[$($args)*] => $body
);
match ret {
Some(x) => Ok(x),
None => unreachable!(), // Hopefully
}
}
)*
_ => std::result::Result::Err(vec),
}
}
};
}
#[test]
fn test() {
let test = |v: Vec<Option<isize>>| {
match_vec!(v.into_iter();
[Some(_x), None, None] => 4,
[Some(_x), None] => 2,
[None, Some(y)] => 1,
[None, _y..] => 3,
[_x.., Some(y), Some(z), None] => y - z,
[Some(ys)..] => ys.sum(),
[] => 0,
[..] => -1,
)
.unwrap()
};
assert_eq!(test(vec![Some(0), None, None]), 4);
assert_eq!(test(vec![Some(0), None]), 2);
assert_eq!(test(vec![None, Some(0)]), 1);
assert_eq!(test(vec![Some(1), Some(2), Some(5), Some(14), None]), -9);
assert_eq!(test(vec![Some(1), Some(2), Some(3), Some(4)]), 10);
assert_eq!(test(vec![None]), 3);
assert_eq!(test(vec![]), 0);
assert_eq!(test(vec![Some(0), None, Some(1)]), -1);
// Test move out of pattern
#[derive(Debug)]
struct Foo;
let _: (Foo, Foo) = match_vec!(vec![Some(Foo), Some(Foo)];
[Some(f1), Some(f2)] => (f1, f2),
)
.unwrap();
// Test return ownership if no match
let _: Vec<Foo> = match_vec!(vec![Foo];
[] => "Error".to_string(),
)
.unwrap_err();
}
|