Debian Codegraph @

debian/rust-vendor/itertools/tests/specializations.rs

raw
1 //! Test specializations of methods with default impls match the behavior of the
2 //! default impls.
3 //!
4 //! **NOTE:** Due to performance limitations, these tests are not run with miri!
5 //! They cannot be relied upon to discover soundness issues.
6
7 #![cfg(not(miri))]
8 #![allow(unstable_name_collisions)]
9
10 use itertools::Itertools;
11 use quickcheck::Arbitrary;
12 use quickcheck::{quickcheck, TestResult};
13 use rand::Rng;
14 use std::fmt::Debug;
15
16 struct Unspecialized<I>(I);
17
18 impl<I> Iterator for Unspecialized<I>
19 where
20 I: Iterator,
21 {
22 type Item = I::Item;
23
24 #[inline(always)]
25 fn next(&mut self) -> Option<Self::Item> {
26 self.0.next()
27 }
28 }
29
30 impl<I> DoubleEndedIterator for Unspecialized<I>
31 where
32 I: DoubleEndedIterator,
33 {
34 #[inline(always)]
35 fn next_back(&mut self) -> Option<Self::Item> {
36 self.0.next_back()
37 }
38 }
39
40 fn test_specializations<I>(it: &I)
41 where
42 I::Item: Eq + Debug + Clone,
43 I: Iterator + Clone,
44 {
45 macro_rules! check_specialized {
46 ($src:expr, |$it:pat| $closure:expr) => {
47 // Many iterators special-case the first elements, so we test specializations for iterators that have already been advanced.
48 let mut src = $src.clone();
49 for _ in 0..5 {
50 let $it = src.clone();
51 let v1 = $closure;
52 let $it = Unspecialized(src.clone());
53 let v2 = $closure;
54 assert_eq!(v1, v2);
55 src.next();
56 }
57 }
58 }
59 check_specialized!(it, |i| i.count());
60 check_specialized!(it, |i| i.last());
61 check_specialized!(it, |i| i.collect::<Vec<_>>());
62 check_specialized!(it, |i| {
63 let mut parameters_from_fold = vec![];
64 let fold_result = i.fold(vec![], |mut acc, v: I::Item| {
65 parameters_from_fold.push((acc.clone(), v.clone()));
66 acc.push(v);
67 acc
68 });
69 (parameters_from_fold, fold_result)
70 });
71 check_specialized!(it, |mut i| {
72 let mut parameters_from_all = vec![];
73 let first = i.next();
74 let all_result = i.all(|x| {
75 parameters_from_all.push(x.clone());
76 Some(x) == first
77 });
78 (parameters_from_all, all_result)
79 });
80 let size = it.clone().count();
81 for n in 0..size + 2 {
82 check_specialized!(it, |mut i| i.nth(n));
83 }
84 // size_hint is a bit harder to check
85 let mut it_sh = it.clone();
86 for n in 0..size + 2 {
87 let len = it_sh.clone().count();
88 let (min, max) = it_sh.size_hint();
89 assert_eq!(size - n.min(size), len);
90 assert!(min <= len);
91 if let Some(max) = max {
92 assert!(len <= max);
93 }
94 it_sh.next();
95 }
96 }
97
98 fn test_double_ended_specializations<I>(it: &I)
99 where
100 I::Item: Eq + Debug + Clone,
101 I: DoubleEndedIterator + Clone,
102 {
103 macro_rules! check_specialized {
104 ($src:expr, |$it:pat| $closure:expr) => {
105 // Many iterators special-case the first elements, so we test specializations for iterators that have already been advanced.
106 let mut src = $src.clone();
107 for step in 0..8 {
108 let $it = src.clone();
109 let v1 = $closure;
110 let $it = Unspecialized(src.clone());
111 let v2 = $closure;
112 assert_eq!(v1, v2);
113 if step % 2 == 0 {
114 src.next();
115 } else {
116 src.next_back();
117 }
118 }
119 }
120 }
121 check_specialized!(it, |i| {
122 let mut parameters_from_rfold = vec![];
123 let rfold_result = i.rfold(vec![], |mut acc, v: I::Item| {
124 parameters_from_rfold.push((acc.clone(), v.clone()));
125 acc.push(v);
126 acc
127 });
128 (parameters_from_rfold, rfold_result)
129 });
130 let size = it.clone().count();
131 for n in 0..size + 2 {
132 check_specialized!(it, |mut i| i.nth_back(n));
133 }
134 }
135
136 quickcheck! {
137 fn interleave(v: Vec<u8>, w: Vec<u8>) -> () {
138 test_specializations(&v.iter().interleave(w.iter()));
139 }
140
141 fn interleave_shortest(v: Vec<u8>, w: Vec<u8>) -> () {
142 test_specializations(&v.iter().interleave_shortest(w.iter()));
143 }
144
145 fn batching(v: Vec<u8>) -> () {
146 test_specializations(&v.iter().batching(Iterator::next));
147 }
148
149 fn tuple_windows(v: Vec<u8>) -> () {
150 test_specializations(&v.iter().tuple_windows::<(_,)>());
151 test_specializations(&v.iter().tuple_windows::<(_, _)>());
152 test_specializations(&v.iter().tuple_windows::<(_, _, _)>());
153 }
154
155 fn circular_tuple_windows(v: Vec<u8>) -> () {
156 test_specializations(&v.iter().circular_tuple_windows::<(_,)>());
157 test_specializations(&v.iter().circular_tuple_windows::<(_, _)>());
158 test_specializations(&v.iter().circular_tuple_windows::<(_, _, _)>());
159 }
160
161 fn tuples(v: Vec<u8>) -> () {
162 test_specializations(&v.iter().tuples::<(_,)>());
163 test_specializations(&v.iter().tuples::<(_, _)>());
164 test_specializations(&v.iter().tuples::<(_, _, _)>());
165 }
166
167 fn cartesian_product(a: Vec<u8>, b: Vec<u8>) -> TestResult {
168 if a.len() * b.len() > 100 {
169 return TestResult::discard();
170 }
171 test_specializations(&a.iter().cartesian_product(&b));
172 TestResult::passed()
173 }
174
175 fn multi_cartesian_product(a: Vec<u8>, b: Vec<u8>, c: Vec<u8>) -> TestResult {
176 if a.len() * b.len() * c.len() > 100 {
177 return TestResult::discard();
178 }
179 test_specializations(&vec![a, b, c].into_iter().multi_cartesian_product());
180 TestResult::passed()
181 }
182
183 fn coalesce(v: Vec<u8>) -> () {
184 test_specializations(&v.iter().coalesce(|x, y| if x == y { Ok(x) } else { Err((x, y)) }))
185 }
186
187 fn dedup(v: Vec<u8>) -> () {
188 test_specializations(&v.iter().dedup())
189 }
190
191 fn dedup_by(v: Vec<u8>) -> () {
192 test_specializations(&v.iter().dedup_by(PartialOrd::ge))
193 }
194
195 fn dedup_with_count(v: Vec<u8>) -> () {
196 test_specializations(&v.iter().dedup_with_count())
197 }
198
199 fn dedup_by_with_count(v: Vec<u8>) -> () {
200 test_specializations(&v.iter().dedup_by_with_count(PartialOrd::ge))
201 }
202
203 fn duplicates(v: Vec<u8>) -> () {
204 let it = v.iter().duplicates();
205 test_specializations(&it);
206 test_double_ended_specializations(&it);
207 }
208
209 fn duplicates_by(v: Vec<u8>) -> () {
210 let it = v.iter().duplicates_by(|x| *x % 10);
211 test_specializations(&it);
212 test_double_ended_specializations(&it);
213 }
214
215 fn unique(v: Vec<u8>) -> () {
216 let it = v.iter().unique();
217 test_specializations(&it);
218 test_double_ended_specializations(&it);
219 }
220
221 fn unique_by(v: Vec<u8>) -> () {
222 let it = v.iter().unique_by(|x| *x % 50);
223 test_specializations(&it);
224 test_double_ended_specializations(&it);
225 }
226
227 fn take_while_inclusive(v: Vec<u8>) -> () {
228 test_specializations(&v.iter().copied().take_while_inclusive(|&x| x < 100));
229 }
230
231 fn while_some(v: Vec<u8>) -> () {
232 test_specializations(&v.iter().map(|&x| if x < 100 { Some(2 * x) } else { None }).while_some());
233 }
234
235 fn pad_using(v: Vec<u8>) -> () {
236 use std::convert::TryFrom;
237 let it = v.iter().copied().pad_using(10, |i| u8::try_from(5 * i).unwrap_or(u8::MAX));
238 test_specializations(&it);
239 test_double_ended_specializations(&it);
240 }
241
242 fn with_position(v: Vec<u8>) -> () {
243 test_specializations(&v.iter().with_position());
244 }
245
246 fn positions(v: Vec<u8>) -> () {
247 let it = v.iter().positions(|x| x % 5 == 0);
248 test_specializations(&it);
249 test_double_ended_specializations(&it);
250 }
251
252 fn update(v: Vec<u8>) -> () {
253 let it = v.iter().copied().update(|x| *x = x.wrapping_mul(7));
254 test_specializations(&it);
255 test_double_ended_specializations(&it);
256 }
257
258 #[allow(deprecated)]
259 fn tuple_combinations(v: Vec<u8>) -> TestResult {
260 if v.len() > 10 {
261 return TestResult::discard();
262 }
263 test_specializations(&v.iter().tuple_combinations::<(_,)>());
264 test_specializations(&v.iter().tuple_combinations::<(_, _)>());
265 test_specializations(&v.iter().tuple_combinations::<(_, _, _)>());
266 TestResult::passed()
267 }
268
269 fn intersperse(v: Vec<u8>) -> () {
270 test_specializations(&v.into_iter().intersperse(0));
271 }
272
273 fn intersperse_with(v: Vec<u8>) -> () {
274 test_specializations(&v.into_iter().intersperse_with(|| 0));
275 }
276
277 fn array_combinations(v: Vec<u8>) -> TestResult {
278 if v.len() > 10 {
279 return TestResult::discard();
280 }
281 test_specializations(&v.iter().array_combinations::<1>());
282 test_specializations(&v.iter().array_combinations::<2>());
283 test_specializations(&v.iter().array_combinations::<3>());
284 TestResult::passed()
285 }
286
287 fn combinations(a: Vec<u8>, n: u8) -> TestResult {
288 if n > 3 || a.len() > 8 {
289 return TestResult::discard();
290 }
291 test_specializations(&a.iter().combinations(n as usize));
292 TestResult::passed()
293 }
294
295 fn combinations_with_replacement(a: Vec<u8>, n: u8) -> TestResult {
296 if n > 3 || a.len() > 7 {
297 return TestResult::discard();
298 }
299 test_specializations(&a.iter().combinations_with_replacement(n as usize));
300 TestResult::passed()
301 }
302
303 fn array_combinations_with_replacement(a: Vec<u8>) -> TestResult {
304 if a.len() > 10 {
305 return TestResult::discard();
306 }
307 test_specializations(&a.iter().array_combinations_with_replacement::<1>());
308 test_specializations(&a.iter().array_combinations_with_replacement::<2>());
309 test_specializations(&a.iter().array_combinations_with_replacement::<3>());
310
311 TestResult::passed()
312 }
313 fn permutations(a: Vec<u8>, n: u8) -> TestResult {
314 if n > 3 || a.len() > 8 {
315 return TestResult::discard();
316 }
317 test_specializations(&a.iter().permutations(n as usize));
318 TestResult::passed()
319 }
320
321 fn powerset(a: Vec<u8>) -> TestResult {
322 if a.len() > 6 {
323 return TestResult::discard();
324 }
325 test_specializations(&a.iter().powerset());
326 TestResult::passed()
327 }
328
329 fn zip_longest(a: Vec<u8>, b: Vec<u8>) -> () {
330 let it = a.into_iter().zip_longest(b);
331 test_specializations(&it);
332 test_double_ended_specializations(&it);
333 }
334
335 fn zip_eq(a: Vec<u8>) -> () {
336 test_specializations(&a.iter().zip_eq(a.iter().rev()))
337 }
338
339 fn multizip(a: Vec<u8>) -> () {
340 let it = itertools::multizip((a.iter(), a.iter().rev(), a.iter().take(50)));
341 test_specializations(&it);
342 test_double_ended_specializations(&it);
343 }
344
345 fn izip(a: Vec<u8>, b: Vec<u8>) -> () {
346 test_specializations(&itertools::izip!(b.iter(), a, b.iter().rev()));
347 }
348
349 fn iproduct(a: Vec<u8>, b: Vec<u8>, c: Vec<u8>) -> TestResult {
350 if a.len() * b.len() * c.len() > 200 {
351 return TestResult::discard();
352 }
353 test_specializations(&itertools::iproduct!(a, b.iter(), c));
354 TestResult::passed()
355 }
356
357 fn repeat_n(element: i8, n: u8) -> () {
358 let it = itertools::repeat_n(element, n as usize);
359 test_specializations(&it);
360 test_double_ended_specializations(&it);
361 }
362
363 fn exactly_one_error(v: Vec<u8>) -> TestResult {
364 // Use `at_most_one` would be similar.
365 match v.iter().exactly_one() {
366 Ok(_) => TestResult::discard(),
367 Err(it) => {
368 test_specializations(&it);
369 TestResult::passed()
370 }
371 }
372 }
373 }
374
375 quickcheck! {
376 fn put_back_qc(test_vec: Vec<i32>) -> () {
377 test_specializations(&itertools::put_back(test_vec.iter()));
378 let mut pb = itertools::put_back(test_vec.into_iter());
379 pb.put_back(1);
380 test_specializations(&pb);
381 }
382
383 fn put_back_n(v: Vec<u8>, n: u8) -> () {
384 let mut it = itertools::put_back_n(v);
385 for k in 0..n {
386 it.put_back(k);
387 }
388 test_specializations(&it);
389 }
390
391 fn multipeek(v: Vec<u8>, n: u8) -> () {
392 let mut it = v.into_iter().multipeek();
393 for _ in 0..n {
394 it.peek();
395 }
396 test_specializations(&it);
397 }
398
399 fn peek_nth_with_peek(v: Vec<u8>, n: u8) -> () {
400 let mut it = itertools::peek_nth(v);
401 for _ in 0..n {
402 it.peek();
403 }
404 test_specializations(&it);
405 }
406
407 fn peek_nth_with_peek_nth(v: Vec<u8>, n: u8) -> () {
408 let mut it = itertools::peek_nth(v);
409 it.peek_nth(n as usize);
410 test_specializations(&it);
411 }
412
413 fn peek_nth_with_peek_mut(v: Vec<u8>, n: u8) -> () {
414 let mut it = itertools::peek_nth(v);
415 for _ in 0..n {
416 if let Some(x) = it.peek_mut() {
417 *x = x.wrapping_add(50);
418 }
419 }
420 test_specializations(&it);
421 }
422
423 fn peek_nth_with_peek_nth_mut(v: Vec<u8>, n: u8) -> () {
424 let mut it = itertools::peek_nth(v);
425 if let Some(x) = it.peek_nth_mut(n as usize) {
426 *x = x.wrapping_add(50);
427 }
428 test_specializations(&it);
429 }
430 }
431
432 quickcheck! {
433 fn merge(a: Vec<u8>, b: Vec<u8>) -> () {
434 test_specializations(&a.into_iter().merge(b))
435 }
436
437 fn merge_by(a: Vec<u8>, b: Vec<u8>) -> () {
438 test_specializations(&a.into_iter().merge_by(b, PartialOrd::ge))
439 }
440
441 fn merge_join_by_ordering(i1: Vec<u8>, i2: Vec<u8>) -> () {
442 test_specializations(&i1.into_iter().merge_join_by(i2, Ord::cmp));
443 }
444
445 fn merge_join_by_bool(i1: Vec<u8>, i2: Vec<u8>) -> () {
446 test_specializations(&i1.into_iter().merge_join_by(i2, PartialOrd::ge));
447 }
448
449 fn kmerge(a: Vec<i8>, b: Vec<i8>, c: Vec<i8>) -> () {
450 test_specializations(&vec![a, b, c]
451 .into_iter()
452 .map(|v| v.into_iter().sorted())
453 .kmerge());
454 }
455
456 fn kmerge_by(a: Vec<i8>, b: Vec<i8>, c: Vec<i8>) -> () {
457 test_specializations(&vec![a, b, c]
458 .into_iter()
459 .map(|v| v.into_iter().sorted_by_key(|a| a.abs()))
460 .kmerge_by(|a, b| a.abs() < b.abs()));
461 }
462 }
463
464 quickcheck! {
465 fn map_into(v: Vec<u8>) -> () {
466 let it = v.into_iter().map_into::<u32>();
467 test_specializations(&it);
468 test_double_ended_specializations(&it);
469 }
470
471 fn map_ok(v: Vec<Result<u8, char>>) -> () {
472 let it = v.into_iter().map_ok(|u| u.checked_add(1));
473 test_specializations(&it);
474 test_double_ended_specializations(&it);
475 }
476
477 fn filter_ok(v: Vec<Result<u8, char>>) -> () {
478 let it = v.into_iter().filter_ok(|&i| i < 20);
479 test_specializations(&it);
480 test_double_ended_specializations(&it);
481 }
482
483 fn filter_map_ok(v: Vec<Result<u8, char>>) -> () {
484 let it = v.into_iter().filter_map_ok(|i| if i < 20 { Some(i * 2) } else { None });
485 test_specializations(&it);
486 test_double_ended_specializations(&it);
487 }
488
489 // `SmallIter2<u8>` because `Vec<u8>` is too slow and we get bad coverage from a singleton like Option<u8>
490 fn flatten_ok(v: Vec<Result<SmallIter2<u8>, char>>) -> () {
491 let it = v.into_iter().flatten_ok();
492 test_specializations(&it);
493 test_double_ended_specializations(&it);
494 }
495 }
496
497 quickcheck! {
498 // TODO Replace this function by a normal call to test_specializations
499 fn process_results(v: Vec<Result<u8, u8>>) -> () {
500 helper(v.iter().copied());
501 helper(v.iter().copied().filter(Result::is_ok));
502
503 fn helper(it: impl DoubleEndedIterator<Item = Result<u8, u8>> + Clone) {
504 macro_rules! check_results_specialized {
505 ($src:expr, |$it:pat| $closure:expr) => {
506 assert_eq!(
507 itertools::process_results($src.clone(), |$it| $closure),
508 itertools::process_results($src.clone(), |i| {
509 let $it = Unspecialized(i);
510 $closure
511 }),
512 )
513 }
514 }
515
516 check_results_specialized!(it, |i| i.count());
517 check_results_specialized!(it, |i| {
518 #[allow(clippy::double_ended_iterator_last)]
519 i.last()
520 });
521 check_results_specialized!(it, |i| i.collect::<Vec<_>>());
522 check_results_specialized!(it, |i| i.rev().collect::<Vec<_>>());
523 check_results_specialized!(it, |i| {
524 let mut parameters_from_fold = vec![];
525 let fold_result = i.fold(vec![], |mut acc, v| {
526 parameters_from_fold.push((acc.clone(), v));
527 acc.push(v);
528 acc
529 });
530 (parameters_from_fold, fold_result)
531 });
532 check_results_specialized!(it, |i| {
533 let mut parameters_from_rfold = vec![];
534 let rfold_result = i.rfold(vec![], |mut acc, v| {
535 parameters_from_rfold.push((acc.clone(), v));
536 acc.push(v);
537 acc
538 });
539 (parameters_from_rfold, rfold_result)
540 });
541 check_results_specialized!(it, |mut i| {
542 let mut parameters_from_all = vec![];
543 let first = i.next();
544 let all_result = i.all(|x| {
545 parameters_from_all.push(x);
546 Some(x)==first
547 });
548 (parameters_from_all, all_result)
549 });
550 let size = it.clone().count();
551 for n in 0..size + 2 {
552 check_results_specialized!(it, |mut i| i.nth(n));
553 }
554 for n in 0..size + 2 {
555 check_results_specialized!(it, |mut i| i.nth_back(n));
556 }
557 }
558 }
559 }
560
561 /// Like `VecIntoIter<T>` with maximum 2 elements.
562 #[derive(Debug, Clone, Default)]
563 enum SmallIter2<T> {
564 #[default]
565 Zero,
566 One(T),
567 Two(T, T),
568 }
569
570 impl<T: Arbitrary> Arbitrary for SmallIter2<T> {
571 fn arbitrary<G: quickcheck::Gen>(g: &mut G) -> Self {
572 match g.gen_range(0u8, 3) {
573 0 => Self::Zero,
574 1 => Self::One(T::arbitrary(g)),
575 2 => Self::Two(T::arbitrary(g), T::arbitrary(g)),
576 _ => unreachable!(),
577 }
578 }
579 // maybe implement shrink too, maybe not
580 }
581
582 impl<T> Iterator for SmallIter2<T> {
583 type Item = T;
584
585 fn next(&mut self) -> Option<Self::Item> {
586 match std::mem::take(self) {
587 Self::Zero => None,
588 Self::One(val) => Some(val),
589 Self::Two(val, second) => {
590 *self = Self::One(second);
591 Some(val)
592 }
593 }
594 }
595
596 fn size_hint(&self) -> (usize, Option<usize>) {
597 let len = match self {
598 Self::Zero => 0,
599 Self::One(_) => 1,
600 Self::Two(_, _) => 2,
601 };
602 (len, Some(len))
603 }
604 }
605
606 impl<T> DoubleEndedIterator for SmallIter2<T> {
607 fn next_back(&mut self) -> Option<Self::Item> {
608 match std::mem::take(self) {
609 Self::Zero => None,
610 Self::One(val) => Some(val),
611 Self::Two(first, val) => {
612 *self = Self::One(first);
613 Some(val)
614 }
615 }
616 }
617 }