Debian Codegraph @

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

raw
1 //! The purpose of these tests is to cover corner cases of iterators
2 //! and adaptors.
3 //!
4 //! In particular we test the tedious size_hint and exact size correctness.
5 //!
6 //! **NOTE:** Due to performance limitations, these tests are not run with miri!
7 //! They cannot be relied upon to discover soundness issues.
8
9 #![cfg(not(miri))]
10 #![allow(deprecated, unstable_name_collisions)]
11
12 use itertools::free::{
13 cloned, enumerate, multipeek, peek_nth, put_back, put_back_n, rciter, zip, zip_eq,
14 };
15 use itertools::Itertools;
16 use itertools::{iproduct, izip, multizip, EitherOrBoth};
17 use quickcheck as qc;
18 use std::cmp::{max, min, Ordering};
19 use std::collections::{HashMap, HashSet};
20 use std::default::Default;
21 use std::num::Wrapping;
22 use std::ops::Range;
23
24 use quickcheck::TestResult;
25 use rand::seq::SliceRandom;
26 use rand::Rng;
27
28 /// Trait for size hint modifier types
29 trait HintKind: Copy + Send + qc::Arbitrary {
30 fn loosen_bounds(&self, org_hint: (usize, Option<usize>)) -> (usize, Option<usize>);
31 }
32
33 /// Exact size hint variant that leaves hints unchanged
34 #[derive(Clone, Copy, Debug)]
35 struct Exact {}
36
37 impl HintKind for Exact {
38 fn loosen_bounds(&self, org_hint: (usize, Option<usize>)) -> (usize, Option<usize>) {
39 org_hint
40 }
41 }
42
43 impl qc::Arbitrary for Exact {
44 fn arbitrary<G: qc::Gen>(_: &mut G) -> Self {
45 Self {}
46 }
47 }
48
49 /// Inexact size hint variant to simulate imprecise (but valid) size hints
50 ///
51 /// Will always decrease the lower bound and increase the upper bound
52 /// of the size hint by set amounts.
53 #[derive(Clone, Copy, Debug)]
54 struct Inexact {
55 underestimate: usize,
56 overestimate: usize,
57 }
58
59 impl HintKind for Inexact {
60 fn loosen_bounds(&self, org_hint: (usize, Option<usize>)) -> (usize, Option<usize>) {
61 let (org_lower, org_upper) = org_hint;
62 (
63 org_lower.saturating_sub(self.underestimate),
64 org_upper.and_then(move |x| x.checked_add(self.overestimate)),
65 )
66 }
67 }
68
69 impl qc::Arbitrary for Inexact {
70 fn arbitrary<G: qc::Gen>(g: &mut G) -> Self {
71 let ue_value = usize::arbitrary(g);
72 let oe_value = usize::arbitrary(g);
73 // Compensate for quickcheck using extreme values too rarely
74 let ue_choices = &[0, ue_value, usize::MAX];
75 let oe_choices = &[0, oe_value, usize::MAX];
76 Self {
77 underestimate: *ue_choices.choose(g).unwrap(),
78 overestimate: *oe_choices.choose(g).unwrap(),
79 }
80 }
81
82 fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
83 let underestimate_value = self.underestimate;
84 let overestimate_value = self.overestimate;
85 Box::new(underestimate_value.shrink().flat_map(move |ue_value| {
86 overestimate_value.shrink().map(move |oe_value| Self {
87 underestimate: ue_value,
88 overestimate: oe_value,
89 })
90 }))
91 }
92 }
93
94 /// Our base iterator that we can impl Arbitrary for
95 ///
96 /// By default we'll return inexact bounds estimates for size_hint
97 /// to make tests harder to pass.
98 ///
99 /// NOTE: Iter is tricky and is not fused, to help catch bugs.
100 /// At the end it will return None once, then return Some(0),
101 /// then return None again.
102 #[derive(Clone, Debug)]
103 struct Iter<T, SK: HintKind = Inexact> {
104 iterator: Range<T>,
105 // fuse/done flag
106 fuse_flag: i32,
107 hint_kind: SK,
108 }
109
110 impl<T, HK> Iter<T, HK>
111 where
112 HK: HintKind,
113 {
114 fn new(it: Range<T>, hint_kind: HK) -> Self {
115 Self {
116 iterator: it,
117 fuse_flag: 0,
118 hint_kind,
119 }
120 }
121 }
122
123 impl<T, HK> Iterator for Iter<T, HK>
124 where
125 Range<T>: Iterator,
126 <Range<T> as Iterator>::Item: Default,
127 HK: HintKind,
128 {
129 type Item = <Range<T> as Iterator>::Item;
130
131 fn next(&mut self) -> Option<Self::Item> {
132 let elt = self.iterator.next();
133 if elt.is_none() {
134 self.fuse_flag += 1;
135 // check fuse flag
136 if self.fuse_flag == 2 {
137 return Some(Default::default());
138 }
139 }
140 elt
141 }
142
143 fn size_hint(&self) -> (usize, Option<usize>) {
144 let org_hint = self.iterator.size_hint();
145 self.hint_kind.loosen_bounds(org_hint)
146 }
147 }
148
149 impl<T, HK> DoubleEndedIterator for Iter<T, HK>
150 where
151 Range<T>: DoubleEndedIterator,
152 <Range<T> as Iterator>::Item: Default,
153 HK: HintKind,
154 {
155 fn next_back(&mut self) -> Option<Self::Item> {
156 self.iterator.next_back()
157 }
158 }
159
160 impl<T> ExactSizeIterator for Iter<T, Exact>
161 where
162 Range<T>: ExactSizeIterator,
163 <Range<T> as Iterator>::Item: Default,
164 {
165 }
166
167 impl<T, HK> qc::Arbitrary for Iter<T, HK>
168 where
169 T: qc::Arbitrary,
170 HK: HintKind,
171 {
172 fn arbitrary<G: qc::Gen>(g: &mut G) -> Self {
173 Self::new(T::arbitrary(g)..T::arbitrary(g), HK::arbitrary(g))
174 }
175
176 fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
177 let r = self.iterator.clone();
178 let hint_kind = self.hint_kind;
179 Box::new(r.start.shrink().flat_map(move |a| {
180 r.end
181 .shrink()
182 .map(move |b| Self::new(a.clone()..b, hint_kind))
183 }))
184 }
185 }
186
187 /// A meta-iterator which yields `Iter<i32>`s whose start/endpoints are
188 /// increased or decreased linearly on each iteration.
189 #[derive(Clone, Debug)]
190 struct ShiftRange<HK = Inexact> {
191 range_start: i32,
192 range_end: i32,
193 start_step: i32,
194 end_step: i32,
195 iter_count: u32,
196 hint_kind: HK,
197 }
198
199 impl<HK> Iterator for ShiftRange<HK>
200 where
201 HK: HintKind,
202 {
203 type Item = Iter<i32, HK>;
204
205 fn next(&mut self) -> Option<Self::Item> {
206 if self.iter_count == 0 {
207 return None;
208 }
209
210 let iter = Iter::new(self.range_start..self.range_end, self.hint_kind);
211
212 self.range_start += self.start_step;
213 self.range_end += self.end_step;
214 self.iter_count -= 1;
215
216 Some(iter)
217 }
218 }
219
220 impl ExactSizeIterator for ShiftRange<Exact> {}
221
222 impl<HK> qc::Arbitrary for ShiftRange<HK>
223 where
224 HK: HintKind,
225 {
226 fn arbitrary<G: qc::Gen>(g: &mut G) -> Self {
227 const MAX_STARTING_RANGE_DIFF: i32 = 32;
228 const MAX_STEP_MODULO: i32 = 8;
229 const MAX_ITER_COUNT: u32 = 3;
230
231 let range_start = qc::Arbitrary::arbitrary(g);
232 let range_end = range_start + g.gen_range(0, MAX_STARTING_RANGE_DIFF + 1);
233 let start_step = g.gen_range(-MAX_STEP_MODULO, MAX_STEP_MODULO + 1);
234 let end_step = g.gen_range(-MAX_STEP_MODULO, MAX_STEP_MODULO + 1);
235 let iter_count = g.gen_range(0, MAX_ITER_COUNT + 1);
236 let hint_kind = qc::Arbitrary::arbitrary(g);
237
238 Self {
239 range_start,
240 range_end,
241 start_step,
242 end_step,
243 iter_count,
244 hint_kind,
245 }
246 }
247 }
248
249 fn correct_count<I, F>(get_it: F) -> bool
250 where
251 I: Iterator,
252 F: Fn() -> I,
253 {
254 let mut counts = vec![get_it().count()];
255
256 'outer: loop {
257 let mut it = get_it();
258
259 for _ in 0..(counts.len() - 1) {
260 if it.next().is_none() {
261 panic!("Iterator shouldn't be finished, may not be deterministic");
262 }
263 }
264
265 if it.next().is_none() {
266 break 'outer;
267 }
268
269 counts.push(it.count());
270 }
271
272 let total_actual_count = counts.len() - 1;
273
274 for (i, returned_count) in counts.into_iter().enumerate() {
275 let actual_count = total_actual_count - i;
276 if actual_count != returned_count {
277 println!(
278 "Total iterations: {i} True count: {actual_count} returned count: {returned_count}"
279 );
280
281 return false;
282 }
283 }
284
285 true
286 }
287
288 fn correct_size_hint<I: Iterator>(mut it: I) -> bool {
289 // record size hint at each iteration
290 let initial_hint = it.size_hint();
291 let mut hints = Vec::with_capacity(initial_hint.0 + 1);
292 hints.push(initial_hint);
293 while let Some(_) = it.next() {
294 hints.push(it.size_hint())
295 }
296
297 let mut true_count = hints.len(); // start off +1 too much
298
299 // check all the size hints
300 for &(low, hi) in &hints {
301 true_count -= 1;
302 if low > true_count || (hi.is_some() && hi.unwrap() < true_count) {
303 println!("True size: {:?}, size hint: {:?}", true_count, (low, hi));
304 //println!("All hints: {:?}", hints);
305 return false;
306 }
307 }
308 true
309 }
310
311 fn exact_size<I: ExactSizeIterator>(mut it: I) -> bool {
312 // check every iteration
313 let (mut low, mut hi) = it.size_hint();
314 if Some(low) != hi {
315 return false;
316 }
317 while let Some(_) = it.next() {
318 let (xlow, xhi) = it.size_hint();
319 if low != xlow + 1 {
320 return false;
321 }
322 low = xlow;
323 hi = xhi;
324 if Some(low) != hi {
325 return false;
326 }
327 }
328 let (low, hi) = it.size_hint();
329 low == 0 && hi == Some(0)
330 }
331
332 // Exact size for this case, without ExactSizeIterator
333 fn exact_size_for_this<I: Iterator>(mut it: I) -> bool {
334 // check every iteration
335 let (mut low, mut hi) = it.size_hint();
336 if Some(low) != hi {
337 return false;
338 }
339 while let Some(_) = it.next() {
340 let (xlow, xhi) = it.size_hint();
341 if low != xlow + 1 {
342 return false;
343 }
344 low = xlow;
345 hi = xhi;
346 if Some(low) != hi {
347 return false;
348 }
349 }
350 let (low, hi) = it.size_hint();
351 low == 0 && hi == Some(0)
352 }
353
354 /*
355 * NOTE: Range<i8> is broken!
356 * (all signed ranges are)
357 #[quickcheck]
358 fn size_range_i8(a: Iter<i8>) -> bool {
359 exact_size(a)
360 }
361
362 #[quickcheck]
363 fn size_range_i16(a: Iter<i16>) -> bool {
364 exact_size(a)
365 }
366
367 #[quickcheck]
368 fn size_range_u8(a: Iter<u8>) -> bool {
369 exact_size(a)
370 }
371 */
372
373 macro_rules! quickcheck {
374 // accept several property function definitions
375 // The property functions can use pattern matching and `mut` as usual
376 // in the function arguments, but the functions can not be generic.
377 {$($(#$attr:tt)* fn $fn_name:ident($($arg:tt)*) -> $ret:ty { $($code:tt)* })*} => (
378 $(
379 #[test]
380 $(#$attr)*
381 fn $fn_name() {
382 fn prop($($arg)*) -> $ret {
383 $($code)*
384 }
385 ::quickcheck::quickcheck(quickcheck!(@fn prop [] $($arg)*));
386 }
387 )*
388 );
389 // parse argument list (with patterns allowed) into prop as fn(_, _) -> _
390 (@fn $f:ident [$($t:tt)*]) => {
391 $f as fn($($t),*) -> _
392 };
393 (@fn $f:ident [$($p:tt)*] : $($tail:tt)*) => {
394 quickcheck!(@fn $f [$($p)* _] $($tail)*)
395 };
396 (@fn $f:ident [$($p:tt)*] $t:tt $($tail:tt)*) => {
397 quickcheck!(@fn $f [$($p)*] $($tail)*)
398 };
399 }
400
401 quickcheck! {
402
403 fn size_product(a: Iter<u16>, b: Iter<u16>) -> bool {
404 correct_size_hint(a.cartesian_product(b))
405 }
406 fn size_product3(a: Iter<u16>, b: Iter<u16>, c: Iter<u16>) -> bool {
407 correct_size_hint(iproduct!(a, b, c))
408 }
409
410 fn correct_cartesian_product3(a: Iter<u16>, b: Iter<u16>, c: Iter<u16>,
411 take_manual: usize) -> ()
412 {
413 // test correctness of iproduct through regular iteration (take)
414 // and through fold.
415 let ac = a.clone();
416 let br = &b.clone();
417 let cr = &c.clone();
418 let answer: Vec<_> = ac.flat_map(move |ea| br.clone().flat_map(move |eb| cr.clone().map(move |ec| (ea, eb, ec)))).collect();
419 let mut product_iter = iproduct!(a, b, c);
420 let mut actual = Vec::new();
421
422 actual.extend((&mut product_iter).take(take_manual));
423 if actual.len() == take_manual {
424 product_iter.fold((), |(), elt| actual.push(elt));
425 }
426 assert_eq!(answer, actual);
427 }
428
429 fn size_multi_product(a: ShiftRange) -> bool {
430 correct_size_hint(a.multi_cartesian_product())
431 }
432 fn correct_multi_product3(a: ShiftRange, take_manual: usize) -> () {
433 // Fix no. of iterators at 3
434 let a = ShiftRange { iter_count: 3, ..a };
435
436 // test correctness of MultiProduct through regular iteration (take)
437 // and through fold.
438 let mut iters = a.clone();
439 let i0 = iters.next().unwrap();
440 let i1r = &iters.next().unwrap();
441 let i2r = &iters.next().unwrap();
442 let answer: Vec<_> = i0.flat_map(move |ei0| i1r.clone().flat_map(move |ei1| i2r.clone().map(move |ei2| vec![ei0, ei1, ei2]))).collect();
443 let mut multi_product = a.clone().multi_cartesian_product();
444 let mut actual = Vec::new();
445
446 actual.extend((&mut multi_product).take(take_manual));
447 if actual.len() == take_manual {
448 multi_product.fold((), |(), elt| actual.push(elt));
449 }
450 assert_eq!(answer, actual);
451
452 assert_eq!(
453 {
454 #[allow(clippy::double_ended_iterator_last)]
455 answer.into_iter().last()
456 },
457 a.multi_cartesian_product().last()
458 );
459 }
460
461 fn correct_empty_multi_product() -> () {
462 let empty = Vec::<std::vec::IntoIter<i32>>::new().into_iter().multi_cartesian_product();
463 assert!(correct_size_hint(empty.clone()));
464 itertools::assert_equal(empty, std::iter::once(Vec::new()))
465 }
466
467 fn size_multipeek(a: Iter<u16, Exact>, s: u8) -> bool {
468 let mut it = multipeek(a);
469 // peek a few times
470 for _ in 0..s {
471 it.peek();
472 }
473 exact_size(it)
474 }
475
476 fn size_peek_nth(a: Iter<u16, Exact>, s: u8) -> bool {
477 let mut it = peek_nth(a);
478 // peek a few times
479 for n in 0..s {
480 it.peek_nth(n as usize);
481 }
482 exact_size(it)
483 }
484
485 fn equal_merge(mut a: Vec<i16>, mut b: Vec<i16>) -> bool {
486 a.sort();
487 b.sort();
488 let mut merged = a.clone();
489 merged.extend(b.iter().cloned());
490 merged.sort();
491 itertools::equal(&merged, a.iter().merge(&b))
492 }
493 fn size_merge(a: Iter<u16>, b: Iter<u16>) -> bool {
494 correct_size_hint(a.merge(b))
495 }
496 fn size_zip(a: Iter<i16, Exact>, b: Iter<i16, Exact>, c: Iter<i16, Exact>) -> bool {
497 let filt = a.clone().dedup();
498 correct_size_hint(multizip((filt, b.clone(), c.clone()))) &&
499 exact_size(multizip((a, b, c)))
500 }
501 fn size_zip_rc(a: Iter<i16>, b: Iter<i16>) -> bool {
502 let rc = rciter(a);
503 correct_size_hint(multizip((&rc, &rc, b)))
504 }
505
506 fn size_zip_macro(a: Iter<i16, Exact>, b: Iter<i16, Exact>, c: Iter<i16, Exact>) -> bool {
507 let filt = a.clone().dedup();
508 correct_size_hint(izip!(filt, b.clone(), c.clone())) &&
509 exact_size(izip!(a, b, c))
510 }
511 fn equal_kmerge(mut a: Vec<i16>, mut b: Vec<i16>, mut c: Vec<i16>) -> bool {
512 use itertools::free::kmerge;
513 a.sort();
514 b.sort();
515 c.sort();
516 let mut merged = a.clone();
517 merged.extend(b.iter().cloned());
518 merged.extend(c.iter().cloned());
519 merged.sort();
520 itertools::equal(merged.into_iter(), kmerge(vec![a, b, c]))
521 }
522
523 // Any number of input iterators
524 fn equal_kmerge_2(mut inputs: Vec<Vec<i16>>) -> bool {
525 use itertools::free::kmerge;
526 // sort the inputs
527 for input in &mut inputs {
528 input.sort();
529 }
530 let mut merged = inputs.concat();
531 merged.sort();
532 itertools::equal(merged.into_iter(), kmerge(inputs))
533 }
534
535 // Any number of input iterators
536 fn equal_kmerge_by_ge(mut inputs: Vec<Vec<i16>>) -> bool {
537 // sort the inputs
538 for input in &mut inputs {
539 input.sort();
540 input.reverse();
541 }
542 let mut merged = inputs.concat();
543 merged.sort();
544 merged.reverse();
545 itertools::equal(merged.into_iter(),
546 inputs.into_iter().kmerge_by(|x, y| x >= y))
547 }
548
549 // Any number of input iterators
550 fn equal_kmerge_by_lt(mut inputs: Vec<Vec<i16>>) -> bool {
551 // sort the inputs
552 for input in &mut inputs {
553 input.sort();
554 }
555 let mut merged = inputs.concat();
556 merged.sort();
557 itertools::equal(merged.into_iter(),
558 inputs.into_iter().kmerge_by(|x, y| x < y))
559 }
560
561 // Any number of input iterators
562 fn equal_kmerge_by_le(mut inputs: Vec<Vec<i16>>) -> bool {
563 // sort the inputs
564 for input in &mut inputs {
565 input.sort();
566 }
567 let mut merged = inputs.concat();
568 merged.sort();
569 itertools::equal(merged.into_iter(),
570 inputs.into_iter().kmerge_by(|x, y| x <= y))
571 }
572 fn size_kmerge(a: Iter<i16>, b: Iter<i16>, c: Iter<i16>) -> bool {
573 use itertools::free::kmerge;
574 correct_size_hint(kmerge(vec![a, b, c]))
575 }
576 fn equal_zip_eq(a: Vec<i32>, b: Vec<i32>) -> bool {
577 let len = std::cmp::min(a.len(), b.len());
578 let a = &a[..len];
579 let b = &b[..len];
580 itertools::equal(zip_eq(a, b), zip(a, b))
581 }
582
583 #[should_panic]
584 fn zip_eq_panics(a: Vec<u8>, b: Vec<u8>) -> TestResult {
585 if a.len() == b.len() { return TestResult::discard(); }
586 zip_eq(a.iter(), b.iter()).for_each(|_| {});
587 TestResult::passed() // won't come here
588 }
589
590 fn equal_positions(a: Vec<i32>) -> bool {
591 let with_pos = a.iter().positions(|v| v % 2 == 0);
592 let without = a.iter().enumerate().filter(|(_, v)| *v % 2 == 0).map(|(i, _)| i);
593 itertools::equal(with_pos.clone(), without.clone())
594 && itertools::equal(with_pos.rev(), without.rev())
595 }
596 fn size_zip_longest(a: Iter<i16, Exact>, b: Iter<i16, Exact>) -> bool {
597 let filt = a.clone().dedup();
598 let filt2 = b.clone().dedup();
599 correct_size_hint(filt.zip_longest(b.clone())) &&
600 correct_size_hint(a.clone().zip_longest(filt2)) &&
601 exact_size(a.zip_longest(b))
602 }
603 fn size_2_zip_longest(a: Iter<i16>, b: Iter<i16>) -> bool {
604 let it = a.clone().zip_longest(b.clone());
605 let jt = a.clone().zip_longest(b.clone());
606 itertools::equal(a,
607 it.filter_map(|elt| match elt {
608 EitherOrBoth::Both(x, _) => Some(x),
609 EitherOrBoth::Left(x) => Some(x),
610 _ => None,
611 }
612 ))
613 &&
614 itertools::equal(b,
615 jt.filter_map(|elt| match elt {
616 EitherOrBoth::Both(_, y) => Some(y),
617 EitherOrBoth::Right(y) => Some(y),
618 _ => None,
619 }
620 ))
621 }
622 fn size_interleave(a: Iter<i16>, b: Iter<i16>) -> bool {
623 correct_size_hint(a.interleave(b))
624 }
625 fn exact_interleave(a: Iter<i16, Exact>, b: Iter<i16, Exact>) -> bool {
626 exact_size_for_this(a.interleave(b))
627 }
628 fn size_interleave_shortest(a: Iter<i16>, b: Iter<i16>) -> bool {
629 correct_size_hint(a.interleave_shortest(b))
630 }
631 fn exact_interleave_shortest(a: Vec<()>, b: Vec<()>) -> bool {
632 exact_size_for_this(a.iter().interleave_shortest(&b))
633 }
634 fn size_intersperse(a: Iter<i16>, x: i16) -> bool {
635 correct_size_hint(a.intersperse(x))
636 }
637 fn equal_intersperse(a: Vec<i32>, x: i32) -> bool {
638 let mut inter = false;
639 let mut i = 0;
640 for elt in a.iter().cloned().intersperse(x) {
641 if inter {
642 if elt != x { return false }
643 } else {
644 if elt != a[i] { return false }
645 i += 1;
646 }
647 inter = !inter;
648 }
649 true
650 }
651
652 fn equal_combinations_2(a: Vec<u8>) -> bool {
653 let mut v = Vec::new();
654 for (i, x) in enumerate(&a) {
655 for y in &a[i + 1..] {
656 v.push((x, y));
657 }
658 }
659 itertools::equal(a.iter().tuple_combinations::<(_, _)>(), v)
660 }
661
662 fn collect_tuple_matches_size(a: Iter<i16>) -> bool {
663 let size = a.clone().count();
664 a.collect_tuple::<(_, _, _)>().is_some() == (size == 3)
665 }
666
667 fn correct_permutations(vals: HashSet<i32>, k: usize) -> () {
668 // Test permutations only on iterators of distinct integers, to prevent
669 // false positives.
670
671 const MAX_N: usize = 5;
672
673 let n = min(vals.len(), MAX_N);
674 let vals: HashSet<i32> = vals.into_iter().take(n).collect();
675
676 let perms = vals.iter().permutations(k);
677
678 let mut actual = HashSet::new();
679
680 for perm in perms {
681 assert_eq!(perm.len(), k);
682
683 let all_items_valid = perm.iter().all(|p| vals.contains(p));
684 assert!(all_items_valid, "perm contains value not from input: {:?}", perm);
685
686 // Check that all perm items are distinct
687 let distinct_len = {
688 let perm_set: HashSet<_> = perm.iter().collect();
689 perm_set.len()
690 };
691 assert_eq!(perm.len(), distinct_len);
692
693 // Check that the perm is new
694 assert!(actual.insert(perm.clone()), "perm already encountered: {:?}", perm);
695 }
696 }
697
698 fn permutations_lexic_order(a: usize, b: usize) -> () {
699 let a = a % 6;
700 let b = b % 6;
701
702 let n = max(a, b);
703 let k = min (a, b);
704
705 let expected_first: Vec<usize> = (0..k).collect();
706 let expected_last: Vec<usize> = ((n - k)..n).rev().collect();
707
708 let mut perms = (0..n).permutations(k);
709
710 let mut curr_perm = match perms.next() {
711 Some(p) => p,
712 None => { return; }
713 };
714
715 assert_eq!(expected_first, curr_perm);
716
717 for next_perm in perms {
718 assert!(
719 next_perm > curr_perm,
720 "next perm isn't greater-than current; next_perm={:?} curr_perm={:?} n={}",
721 next_perm, curr_perm, n
722 );
723
724 curr_perm = next_perm;
725 }
726
727 assert_eq!(expected_last, curr_perm);
728
729 }
730
731 fn permutations_count(n: usize, k: usize) -> bool {
732 let n = n % 6;
733
734 correct_count(|| (0..n).permutations(k))
735 }
736
737 fn permutations_size(a: Iter<i32>, k: usize) -> bool {
738 correct_size_hint(a.take(5).permutations(k))
739 }
740
741 fn permutations_k0_yields_once(n: usize) -> () {
742 let k = 0;
743 let expected: Vec<Vec<usize>> = vec![vec![]];
744 let actual = (0..n).permutations(k).collect_vec();
745
746 assert_eq!(expected, actual);
747 }
748 }
749
750 quickcheck! {
751 fn correct_peek_nth(mut a: Vec<u16>) -> () {
752 let mut it = peek_nth(a.clone());
753 for start_pos in 0..a.len() + 2 {
754 for real_idx in start_pos..a.len() + 2 {
755 let peek_idx = real_idx - start_pos;
756 assert_eq!(it.peek_nth(peek_idx), a.get(real_idx));
757 assert_eq!(it.peek_nth_mut(peek_idx), a.get_mut(real_idx));
758 }
759 assert_eq!(it.next(), a.get(start_pos).copied());
760 }
761 }
762
763 fn peek_nth_mut_replace(a: Vec<u16>, b: Vec<u16>) -> () {
764 let mut it = peek_nth(a.iter());
765 for (i, m) in b.iter().enumerate().take(a.len().min(b.len())) {
766 *it.peek_nth_mut(i).unwrap() = m;
767 }
768 for (i, m) in a.iter().enumerate() {
769 assert_eq!(it.next().unwrap(), b.get(i).unwrap_or(m));
770 }
771 assert_eq!(it.next(), None);
772 assert_eq!(it.next(), None);
773 }
774
775 fn peek_nth_next_if(a: Vec<u8>) -> () {
776 let mut it = peek_nth(a.clone());
777 for (idx, mut value) in a.iter().copied().enumerate() {
778 let should_be_none = it.next_if(|x| x != &value);
779 assert_eq!(should_be_none, None);
780 if value % 5 == 0 {
781 // Sometimes, peek up to 3 further.
782 let n = value as usize % 3;
783 let nth = it.peek_nth(n);
784 assert_eq!(nth, a.get(idx + n));
785 } else if value % 5 == 1 {
786 // Sometimes, peek next element mutably.
787 if let Some(v) = it.peek_mut() {
788 *v = v.wrapping_sub(1);
789 let should_be_none = it.next_if_eq(&value);
790 assert_eq!(should_be_none, None);
791 value = value.wrapping_sub(1);
792 }
793 }
794 let eq = it.next_if_eq(&value);
795 assert_eq!(eq, Some(value));
796 }
797 }
798 }
799
800 quickcheck! {
801 fn dedup_via_coalesce(a: Vec<i32>) -> bool {
802 let mut b = a.clone();
803 b.dedup();
804 itertools::equal(
805 &b,
806 a
807 .iter()
808 .coalesce(|x, y| {
809 if x==y {
810 Ok(x)
811 } else {
812 Err((x, y))
813 }
814 })
815 .fold(vec![], |mut v, n| {
816 v.push(n);
817 v
818 })
819 )
820 }
821 }
822
823 quickcheck! {
824 fn equal_dedup(a: Vec<i32>) -> bool {
825 let mut b = a.clone();
826 b.dedup();
827 itertools::equal(&b, a.iter().dedup())
828 }
829 }
830
831 quickcheck! {
832 fn equal_dedup_by(a: Vec<(i32, i32)>) -> bool {
833 let mut b = a.clone();
834 b.dedup_by(|x, y| x.0==y.0);
835 itertools::equal(&b, a.iter().dedup_by(|x, y| x.0==y.0))
836 }
837 }
838
839 quickcheck! {
840 fn size_dedup(a: Vec<i32>) -> bool {
841 correct_size_hint(a.iter().dedup())
842 }
843 }
844
845 quickcheck! {
846 fn size_dedup_by(a: Vec<(i32, i32)>) -> bool {
847 correct_size_hint(a.iter().dedup_by(|x, y| x.0==y.0))
848 }
849 }
850
851 quickcheck! {
852 fn exact_repeatn((n, x): (usize, i32)) -> bool {
853 let it = itertools::repeat_n(x, n);
854 exact_size(it)
855 }
856 }
857
858 quickcheck! {
859 fn size_put_back(a: Vec<u8>, x: Option<u8>) -> bool {
860 let mut it = put_back(a.into_iter());
861 if let Some(t) = x {
862 it.put_back(t);
863 }
864 correct_size_hint(it)
865 }
866 }
867
868 quickcheck! {
869 fn size_put_backn(a: Vec<u8>, b: Vec<u8>) -> bool {
870 let mut it = put_back_n(a.into_iter());
871 for elt in b {
872 it.put_back(elt)
873 }
874 correct_size_hint(it)
875 }
876 }
877
878 quickcheck! {
879 fn merge_join_by_ordering_vs_bool(a: Vec<u8>, b: Vec<u8>) -> bool {
880 use either::Either;
881 use itertools::free::merge_join_by;
882 let mut has_equal = false;
883 let it_ord = merge_join_by(a.clone(), b.clone(), Ord::cmp).flat_map(|v| match v {
884 EitherOrBoth::Both(l, r) => {
885 has_equal = true;
886 vec![Either::Left(l), Either::Right(r)]
887 }
888 EitherOrBoth::Left(l) => vec![Either::Left(l)],
889 EitherOrBoth::Right(r) => vec![Either::Right(r)],
890 });
891 let it_bool = merge_join_by(a, b, PartialOrd::le);
892 itertools::equal(it_ord, it_bool) || has_equal
893 }
894 fn merge_join_by_bool_unwrapped_is_merge_by(a: Vec<u8>, b: Vec<u8>) -> bool {
895 use either::Either;
896 use itertools::free::merge_join_by;
897 let it = a.clone().into_iter().merge_by(b.clone(), PartialOrd::ge);
898 let it_join = merge_join_by(a, b, PartialOrd::ge).map(Either::into_inner);
899 itertools::equal(it, it_join)
900 }
901 }
902
903 quickcheck! {
904 fn size_tee(a: Vec<u8>) -> bool {
905 let (mut t1, mut t2) = a.iter().tee();
906 t1.next();
907 t1.next();
908 t2.next();
909 exact_size(t1) && exact_size(t2)
910 }
911 }
912
913 quickcheck! {
914 fn size_tee_2(a: Vec<u8>) -> bool {
915 let (mut t1, mut t2) = a.iter().dedup().tee();
916 t1.next();
917 t1.next();
918 t2.next();
919 correct_size_hint(t1) && correct_size_hint(t2)
920 }
921 }
922
923 quickcheck! {
924 fn size_take_while_ref(a: Vec<u8>, stop: u8) -> bool {
925 correct_size_hint(a.iter().take_while_ref(|x| **x != stop))
926 }
927 }
928
929 quickcheck! {
930 fn equal_partition(a: Vec<i32>) -> bool {
931 let mut a = a;
932 let mut ap = a.clone();
933 let split_index = itertools::partition(&mut ap, |x| *x >= 0);
934 let parted = (0..split_index).all(|i| ap[i] >= 0) &&
935 (split_index..a.len()).all(|i| ap[i] < 0);
936
937 a.sort();
938 ap.sort();
939 parted && (a == ap)
940 }
941 }
942
943 quickcheck! {
944 fn size_combinations(a: Iter<i16>) -> bool {
945 let it = a.clone().tuple_combinations::<(_, _)>();
946 correct_size_hint(it.clone()) && it.count() == binomial(a.count(), 2)
947 }
948
949 fn exact_size_combinations_1(a: Vec<u8>) -> bool {
950 let it = a.iter().tuple_combinations::<(_,)>();
951 exact_size_for_this(it.clone()) && it.count() == binomial(a.len(), 1)
952 }
953 fn exact_size_combinations_2(a: Vec<u8>) -> bool {
954 let it = a.iter().tuple_combinations::<(_, _)>();
955 exact_size_for_this(it.clone()) && it.count() == binomial(a.len(), 2)
956 }
957 fn exact_size_combinations_3(mut a: Vec<u8>) -> bool {
958 a.truncate(15);
959 let it = a.iter().tuple_combinations::<(_, _, _)>();
960 exact_size_for_this(it.clone()) && it.count() == binomial(a.len(), 3)
961 }
962 }
963
964 fn binomial(n: usize, k: usize) -> usize {
965 if k > n {
966 0
967 } else {
968 (n - k + 1..=n).product::<usize>() / (1..=k).product::<usize>()
969 }
970 }
971
972 quickcheck! {
973 fn equal_combinations(it: Iter<i16>) -> bool {
974 let values = it.clone().collect_vec();
975 let mut cmb = it.tuple_combinations();
976 for i in 0..values.len() {
977 for j in i+1..values.len() {
978 let pair = (values[i], values[j]);
979 if pair != cmb.next().unwrap() {
980 return false;
981 }
982 }
983 }
984 cmb.next().is_none()
985 }
986 }
987
988 quickcheck! {
989 fn size_pad_tail(it: Iter<i8>, pad: u8) -> bool {
990 correct_size_hint(it.clone().pad_using(pad as usize, |_| 0)) &&
991 correct_size_hint(it.dropping(1).rev().pad_using(pad as usize, |_| 0))
992 }
993 }
994
995 quickcheck! {
996 fn size_pad_tail2(it: Iter<i8, Exact>, pad: u8) -> bool {
997 exact_size(it.pad_using(pad as usize, |_| 0))
998 }
999 }
1000
1001 quickcheck! {
1002 fn pad_using_next_next_back(v: Vec<i8>) -> () {
1003 let only_oks = v.into_iter().map(Ok).collect::<Vec<_>>();
1004 for elements_required in 0..128 {
1005 let mut oks_then_errs_vector = only_oks.clone();
1006 while oks_then_errs_vector.len() < elements_required {
1007 oks_then_errs_vector.push(Err(oks_then_errs_vector.len()));
1008 }
1009 let oks_then_errs_pad_using = only_oks.iter().copied().pad_using(elements_required, Err);
1010 assert_eq!(
1011 oks_then_errs_pad_using.clone().collect::<Vec<_>>(),
1012 oks_then_errs_vector
1013 );
1014 // Check next, next_back (https://github.com/rust-itertools/itertools/issues/1065)
1015 let mut iter_check = oks_then_errs_vector.into_iter();
1016 let mut iter_real = oks_then_errs_pad_using;
1017 let mut rng = rand::thread_rng();
1018 loop {
1019 let next_or_next_back = if rng.gen_bool(0.5) {
1020 let element_next_check = iter_check.next();
1021 let element_next_real = iter_real.next();
1022 assert_eq!(element_next_check, element_next_real);
1023 element_next_real
1024 } else {
1025 let element_next_back_check = iter_check.next_back();
1026 let element_next_back_real = iter_real.next_back();
1027 assert_eq!(element_next_back_check, element_next_back_real);
1028 element_next_back_real
1029 };
1030 if next_or_next_back.is_none() {
1031 assert!(iter_real.next().is_none());
1032 assert!(iter_real.next_back().is_none());
1033 break;
1034 }
1035 }
1036 }
1037 }
1038 }
1039
1040 quickcheck! {
1041 fn size_powerset(it: Iter<u8, Exact>) -> bool {
1042 // Powerset cardinality gets large very quickly, limit input to keep test fast.
1043 correct_size_hint(it.take(12).powerset())
1044 }
1045 }
1046
1047 quickcheck! {
1048 fn size_duplicates(it: Iter<i8>) -> bool {
1049 correct_size_hint(it.duplicates())
1050 }
1051 }
1052
1053 quickcheck! {
1054 fn size_unique(it: Iter<i8>) -> bool {
1055 correct_size_hint(it.unique())
1056 }
1057
1058 fn count_unique(it: Vec<i8>, take_first: u8) -> () {
1059 let answer = {
1060 let mut v = it.clone();
1061 v.sort(); v.dedup();
1062 v.len()
1063 };
1064 let mut iter = cloned(&it).unique();
1065 let first_count = (&mut iter).take(take_first as usize).count();
1066 let rest_count = iter.count();
1067 assert_eq!(answer, first_count + rest_count);
1068 }
1069 }
1070
1071 quickcheck! {
1072 fn fuzz_chunk_by_lazy_1(it: Iter<u8>) -> bool {
1073 let jt = it.clone();
1074 let chunks = it.chunk_by(|k| *k);
1075 itertools::equal(jt, chunks.into_iter().flat_map(|(_, x)| x))
1076 }
1077 }
1078
1079 quickcheck! {
1080 fn fuzz_chunk_by_lazy_2(data: Vec<u8>) -> bool {
1081 let chunks = data.iter().chunk_by(|k| *k / 10);
1082 let res = itertools::equal(data.iter(), chunks.into_iter().flat_map(|(_, x)| x));
1083 res
1084 }
1085 }
1086
1087 quickcheck! {
1088 fn fuzz_chunk_by_lazy_3(data: Vec<u8>) -> bool {
1089 let grouper = data.iter().chunk_by(|k| *k / 10);
1090 let chunks = grouper.into_iter().collect_vec();
1091 let res = itertools::equal(data.iter(), chunks.into_iter().flat_map(|(_, x)| x));
1092 res
1093 }
1094 }
1095
1096 quickcheck! {
1097 fn fuzz_chunk_by_lazy_duo(data: Vec<u8>, order: Vec<(bool, bool)>) -> bool {
1098 let grouper = data.iter().chunk_by(|k| *k / 3);
1099 let mut chunks1 = grouper.into_iter();
1100 let mut chunks2 = grouper.into_iter();
1101 let mut elts = Vec::<&u8>::new();
1102 let mut old_chunks = Vec::new();
1103
1104 let tup1 = |(_, b)| b;
1105 for &(ord, consume_now) in &order {
1106 let iter = &mut [&mut chunks1, &mut chunks2][usize::from(ord)];
1107 match iter.next() {
1108 Some((_, gr)) => if consume_now {
1109 for og in old_chunks.drain(..) {
1110 elts.extend(og);
1111 }
1112 elts.extend(gr);
1113 } else {
1114 old_chunks.push(gr);
1115 },
1116 None => break,
1117 }
1118 }
1119 for og in old_chunks.drain(..) {
1120 elts.extend(og);
1121 }
1122 for gr in chunks1.map(&tup1) { elts.extend(gr); }
1123 for gr in chunks2.map(&tup1) { elts.extend(gr); }
1124 itertools::assert_equal(&data, elts);
1125 true
1126 }
1127 }
1128
1129 quickcheck! {
1130 fn chunk_clone_equal(a: Vec<u8>, size: u8) -> () {
1131 let mut size = size;
1132 if size == 0 {
1133 size += 1;
1134 }
1135 let it = a.chunks(size as usize);
1136 itertools::assert_equal(it.clone(), it);
1137 }
1138 }
1139
1140 quickcheck! {
1141 fn equal_chunks_lazy(a: Vec<u8>, size: u8) -> bool {
1142 let mut size = size;
1143 if size == 0 {
1144 size += 1;
1145 }
1146 let chunks = a.iter().chunks(size as usize);
1147 let it = a.chunks(size as usize);
1148 for (a, b) in chunks.into_iter().zip(it) {
1149 if !itertools::equal(a, b) {
1150 return false;
1151 }
1152 }
1153 true
1154 }
1155 }
1156
1157 // tuple iterators
1158 quickcheck! {
1159 fn equal_circular_tuple_windows_1(a: Vec<u8>) -> bool {
1160 let x = a.iter().map(|e| (e,) );
1161 let y = a.iter().circular_tuple_windows::<(_,)>();
1162 itertools::assert_equal(x,y);
1163 true
1164 }
1165
1166 fn equal_circular_tuple_windows_2(a: Vec<u8>) -> bool {
1167 let x = (0..a.len()).map(|start_idx| (
1168 &a[start_idx],
1169 &a[(start_idx + 1) % a.len()],
1170 ));
1171 let y = a.iter().circular_tuple_windows::<(_, _)>();
1172 itertools::assert_equal(x,y);
1173 true
1174 }
1175
1176 fn equal_circular_tuple_windows_3(a: Vec<u8>) -> bool {
1177 let x = (0..a.len()).map(|start_idx| (
1178 &a[start_idx],
1179 &a[(start_idx + 1) % a.len()],
1180 &a[(start_idx + 2) % a.len()],
1181 ));
1182 let y = a.iter().circular_tuple_windows::<(_, _, _)>();
1183 itertools::assert_equal(x,y);
1184 true
1185 }
1186
1187 fn equal_circular_tuple_windows_4(a: Vec<u8>) -> bool {
1188 let x = (0..a.len()).map(|start_idx| (
1189 &a[start_idx],
1190 &a[(start_idx + 1) % a.len()],
1191 &a[(start_idx + 2) % a.len()],
1192 &a[(start_idx + 3) % a.len()],
1193 ));
1194 let y = a.iter().circular_tuple_windows::<(_, _, _, _)>();
1195 itertools::assert_equal(x,y);
1196 true
1197 }
1198
1199 fn equal_cloned_circular_tuple_windows(a: Vec<u8>) -> bool {
1200 let x = a.iter().circular_tuple_windows::<(_, _, _, _)>();
1201 let y = x.clone();
1202 itertools::assert_equal(x,y);
1203 true
1204 }
1205
1206 fn equal_cloned_circular_tuple_windows_noninitial(a: Vec<u8>) -> bool {
1207 let mut x = a.iter().circular_tuple_windows::<(_, _, _, _)>();
1208 let _ = x.next();
1209 let y = x.clone();
1210 itertools::assert_equal(x,y);
1211 true
1212 }
1213
1214 fn equal_cloned_circular_tuple_windows_complete(a: Vec<u8>) -> bool {
1215 let mut x = a.iter().circular_tuple_windows::<(_, _, _, _)>();
1216 for _ in x.by_ref() {}
1217 let y = x.clone();
1218 itertools::assert_equal(x,y);
1219 true
1220 }
1221
1222 fn circular_tuple_windows_exact_size(a: Vec<u8>) -> bool {
1223 exact_size(a.iter().circular_tuple_windows::<(_, _, _, _)>())
1224 }
1225
1226 fn equal_tuple_windows_1(a: Vec<u8>) -> bool {
1227 let x = a.windows(1).map(|s| (&s[0], ));
1228 let y = a.iter().tuple_windows::<(_,)>();
1229 itertools::equal(x, y)
1230 }
1231
1232 fn equal_tuple_windows_2(a: Vec<u8>) -> bool {
1233 let x = a.windows(2).map(|s| (&s[0], &s[1]));
1234 let y = a.iter().tuple_windows::<(_, _)>();
1235 itertools::equal(x, y)
1236 }
1237
1238 fn equal_tuple_windows_3(a: Vec<u8>) -> bool {
1239 let x = a.windows(3).map(|s| (&s[0], &s[1], &s[2]));
1240 let y = a.iter().tuple_windows::<(_, _, _)>();
1241 itertools::equal(x, y)
1242 }
1243
1244 fn equal_tuple_windows_4(a: Vec<u8>) -> bool {
1245 let x = a.windows(4).map(|s| (&s[0], &s[1], &s[2], &s[3]));
1246 let y = a.iter().tuple_windows::<(_, _, _, _)>();
1247 itertools::equal(x, y)
1248 }
1249
1250 fn tuple_windows_exact_size_1(a: Vec<u8>) -> bool {
1251 exact_size(a.iter().tuple_windows::<(_,)>())
1252 }
1253
1254 fn tuple_windows_exact_size_4(a: Vec<u8>) -> bool {
1255 exact_size(a.iter().tuple_windows::<(_, _, _, _)>())
1256 }
1257
1258 fn equal_tuples_1(a: Vec<u8>) -> bool {
1259 let x = a.chunks(1).map(|s| (&s[0], ));
1260 let y = a.iter().tuples::<(_,)>();
1261 itertools::equal(x, y)
1262 }
1263
1264 fn equal_tuples_2(a: Vec<u8>) -> bool {
1265 let x = a.chunks(2).filter(|s| s.len() == 2).map(|s| (&s[0], &s[1]));
1266 let y = a.iter().tuples::<(_, _)>();
1267 itertools::equal(x, y)
1268 }
1269
1270 fn equal_tuples_3(a: Vec<u8>) -> bool {
1271 let x = a.chunks(3).filter(|s| s.len() == 3).map(|s| (&s[0], &s[1], &s[2]));
1272 let y = a.iter().tuples::<(_, _, _)>();
1273 itertools::equal(x, y)
1274 }
1275
1276 fn equal_tuples_4(a: Vec<u8>) -> bool {
1277 let x = a.chunks(4).filter(|s| s.len() == 4).map(|s| (&s[0], &s[1], &s[2], &s[3]));
1278 let y = a.iter().tuples::<(_, _, _, _)>();
1279 itertools::equal(x, y)
1280 }
1281
1282 fn exact_tuple_buffer(a: Vec<u8>) -> bool {
1283 let mut iter = a.iter().tuples::<(_, _, _, _)>();
1284 (&mut iter).last();
1285 let buffer = iter.into_buffer();
1286 assert_eq!(buffer.len(), a.len() % 4);
1287 exact_size(buffer)
1288 }
1289
1290 fn tuples_size_hint_inexact(a: Iter<u8>) -> bool {
1291 correct_size_hint(a.clone().tuples::<(_,)>())
1292 && correct_size_hint(a.clone().tuples::<(_, _)>())
1293 && correct_size_hint(a.tuples::<(_, _, _, _)>())
1294 }
1295
1296 fn tuples_size_hint_exact(a: Iter<u8, Exact>) -> bool {
1297 exact_size(a.clone().tuples::<(_,)>())
1298 && exact_size(a.clone().tuples::<(_, _)>())
1299 && exact_size(a.tuples::<(_, _, _, _)>())
1300 }
1301 }
1302
1303 // array iterators
1304 quickcheck! {
1305 fn equal_array_windows_0(a: Vec<u8>) -> bool {
1306 let x = (0..=a.len()).map(|_| [&0u8; 0] );
1307 let y = a.iter().array_windows::<0>();
1308 itertools::assert_equal(x,y);
1309 true
1310 }
1311
1312 fn equal_array_windows_1(a: Vec<u8>) -> bool {
1313 let x = a.iter().map(|e| [e] );
1314 let y = a.iter().array_windows::<1>();
1315 itertools::assert_equal(x,y);
1316 true
1317 }
1318
1319 fn equal_array_windows_2(a: Vec<u8>) -> bool {
1320 let x = (0..a.len().saturating_sub(1)).map(|start_idx| [
1321 &a[start_idx],
1322 &a[start_idx + 1],
1323 ]);
1324 let y = a.iter().array_windows::<2>();
1325 itertools::assert_equal(x,y);
1326 true
1327 }
1328
1329 fn equal_array_windows_3(a: Vec<u8>) -> bool {
1330 let x = (0..a.len().saturating_sub(2)).map(|start_idx| [
1331 &a[start_idx],
1332 &a[start_idx + 1],
1333 &a[start_idx + 2],
1334 ]);
1335 let y = a.iter().array_windows::<3>();
1336 itertools::assert_equal(x,y);
1337 true
1338 }
1339
1340 fn equal_circular_array_windows_0(a: Vec<u8>) -> bool {
1341 let x = a.iter().map(|_| [&0u8; 0] );
1342 let y = a.iter().circular_array_windows::<0>();
1343 itertools::assert_equal(x,y);
1344 true
1345 }
1346
1347 fn equal_circular_array_windows_1(a: Vec<u8>) -> bool {
1348 let x = a.iter().map(|e| [e] );
1349 let y = a.iter().circular_array_windows::<1>();
1350 itertools::assert_equal(x,y);
1351 true
1352 }
1353
1354 fn equal_circular_array_windows_2(a: Vec<u8>) -> bool {
1355 let x = (0..a.len()).map(|start_idx| [
1356 &a[start_idx],
1357 &a[(start_idx + 1) % a.len()],
1358 ]);
1359 let y = a.iter().circular_array_windows::<2>();
1360 itertools::assert_equal(x,y);
1361 true
1362 }
1363
1364 fn equal_circular_array_windows_3(a: Vec<u8>) -> bool {
1365 let x = (0..a.len()).map(|start_idx| [
1366 &a[start_idx],
1367 &a[(start_idx + 1) % a.len()],
1368 &a[(start_idx + 2) % a.len()],
1369 ]);
1370 let y = a.iter().circular_array_windows::<3>();
1371 itertools::assert_equal(x,y);
1372 true
1373 }
1374 }
1375
1376 // with_position
1377 quickcheck! {
1378 fn with_position_exact_size_1(a: Vec<u8>) -> bool {
1379 exact_size_for_this(a.iter().with_position())
1380 }
1381 fn with_position_exact_size_2(a: Iter<u8, Exact>) -> bool {
1382 exact_size_for_this(a.with_position())
1383 }
1384 }
1385
1386 quickcheck! {
1387 fn correct_group_map_modulo_key(a: Vec<u8>, modulo: u8) -> () {
1388 let modulo = if modulo == 0 { 1 } else { modulo }; // Avoid `% 0`
1389 let count = a.len();
1390 let lookup = a.into_iter().map(|i| (i % modulo, i)).into_group_map();
1391
1392 assert_eq!(lookup.values().flat_map(|vals| vals.iter()).count(), count);
1393
1394 for (&key, vals) in lookup.iter() {
1395 assert!(vals.iter().all(|&val| val % modulo == key));
1396 }
1397 }
1398 }
1399
1400 /// A peculiar type: Equality compares both tuple items, but ordering only the
1401 /// first item. This is so we can check the stability property easily.
1402 #[derive(Clone, Debug, PartialEq, Eq)]
1403 struct Val(u32, u32);
1404
1405 impl PartialOrd<Self> for Val {
1406 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1407 Some(self.cmp(other))
1408 }
1409 }
1410
1411 impl Ord for Val {
1412 fn cmp(&self, other: &Self) -> Ordering {
1413 self.0.cmp(&other.0)
1414 }
1415 }
1416
1417 impl qc::Arbitrary for Val {
1418 fn arbitrary<G: qc::Gen>(g: &mut G) -> Self {
1419 let (x, y) = <(u32, u32)>::arbitrary(g);
1420 Self(x, y)
1421 }
1422 fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
1423 Box::new((self.0, self.1).shrink().map(|(x, y)| Self(x, y)))
1424 }
1425 }
1426
1427 quickcheck! {
1428 fn minmax(a: Vec<Val>) -> bool {
1429 use itertools::MinMaxResult;
1430
1431
1432 let minmax = a.iter().minmax();
1433 let expected = match a.len() {
1434 0 => MinMaxResult::NoElements,
1435 1 => MinMaxResult::OneElement(&a[0]),
1436 _ => MinMaxResult::MinMax(a.iter().min().unwrap(),
1437 a.iter().max().unwrap()),
1438 };
1439 minmax == expected
1440 }
1441 }
1442
1443 quickcheck! {
1444 fn minmax_f64(a: Vec<f64>) -> TestResult {
1445 use itertools::MinMaxResult;
1446
1447 if a.iter().any(|x| x.is_nan()) {
1448 return TestResult::discard();
1449 }
1450
1451 let min = cloned(&a).fold1(f64::min);
1452 let max = cloned(&a).fold1(f64::max);
1453
1454 let minmax = cloned(&a).minmax();
1455 let expected = match a.len() {
1456 0 => MinMaxResult::NoElements,
1457 1 => MinMaxResult::OneElement(min.unwrap()),
1458 _ => MinMaxResult::MinMax(min.unwrap(), max.unwrap()),
1459 };
1460 TestResult::from_bool(minmax == expected)
1461 }
1462 }
1463
1464 quickcheck! {
1465 fn tree_reduce_f64(mut a: Vec<f64>) -> TestResult {
1466 fn collapse_adjacent<F>(x: Vec<f64>, mut f: F) -> Vec<f64>
1467 where F: FnMut(f64, f64) -> f64
1468 {
1469 let mut out = Vec::new();
1470 for i in (0..x.len()).step_by(2) {
1471 if i == x.len()-1 {
1472 out.push(x[i])
1473 } else {
1474 out.push(f(x[i], x[i+1]));
1475 }
1476 }
1477 out
1478 }
1479
1480 if a.iter().any(|x| x.is_nan()) {
1481 return TestResult::discard();
1482 }
1483
1484 let actual = a.iter().cloned().tree_reduce(f64::atan2);
1485
1486 while a.len() > 1 {
1487 a = collapse_adjacent(a, f64::atan2);
1488 }
1489 let expected = a.pop();
1490
1491 TestResult::from_bool(actual == expected)
1492 }
1493 }
1494
1495 quickcheck! {
1496 fn exactly_one_i32(a: Vec<i32>) -> TestResult {
1497 let ret = a.iter().cloned().exactly_one();
1498 match a.len() {
1499 1 => TestResult::from_bool(ret.unwrap() == a[0]),
1500 _ => TestResult::from_bool(ret.unwrap_err().eq(a.iter().cloned())),
1501 }
1502 }
1503 }
1504
1505 quickcheck! {
1506 fn exactly_one_count(a: Vec<i32>) -> TestResult {
1507 let ret = a.iter().cloned().exactly_one();
1508 match a.len() {
1509 1 => TestResult::passed(),
1510 len => TestResult::from_bool(len == ret.unwrap_err().count()),
1511 }
1512 }
1513 }
1514
1515 quickcheck! {
1516 fn at_most_one_i32(a: Vec<i32>) -> TestResult {
1517 let ret = a.iter().cloned().at_most_one();
1518 match a.len() {
1519 0 => TestResult::from_bool(ret.unwrap().is_none()),
1520 1 => TestResult::from_bool(ret.unwrap() == Some(a[0])),
1521 _ => TestResult::from_bool(ret.unwrap_err().eq(a.iter().cloned())),
1522 }
1523 }
1524 }
1525
1526 quickcheck! {
1527 fn consistent_grouping_map_with_by(a: Vec<u8>, modulo: u8) -> () {
1528 let modulo = if modulo == 0 { 1 } else { modulo }; // Avoid `% 0`
1529
1530 let lookup_grouping_map = a.iter().copied().map(|i| (i % modulo, i)).into_grouping_map().collect::<Vec<_>>();
1531 let lookup_grouping_map_by = a.iter().copied().into_grouping_map_by(|i| i % modulo).collect::<Vec<_>>();
1532
1533 assert_eq!(lookup_grouping_map, lookup_grouping_map_by);
1534 }
1535
1536 fn correct_grouping_map_by_aggregate_modulo_key(a: Vec<u8>, modulo: u8) -> () {
1537 let modulo = u64::from(if modulo < 2 { 2 } else { modulo }); // Avoid `% 0`
1538 let lookup = a.iter()
1539 .map(|&b| u64::from(b)) // Avoid overflows
1540 .into_grouping_map_by(|i| i % modulo)
1541 .aggregate(|acc, &key, val| {
1542 assert!(val % modulo == key);
1543 if val % (modulo - 1) == 0 {
1544 None
1545 } else {
1546 Some(acc.unwrap_or(0) + val)
1547 }
1548 });
1549
1550 let group_map_lookup = a.iter()
1551 .map(|&b| u64::from(b))
1552 .map(|i| (i % modulo, i))
1553 .into_group_map()
1554 .into_iter()
1555 .filter_map(|(key, vals)| {
1556 vals.into_iter().fold(None, |acc, val| {
1557 if val % (modulo - 1) == 0 {
1558 None
1559 } else {
1560 Some(acc.unwrap_or(0) + val)
1561 }
1562 }).map(|new_val| (key, new_val))
1563 })
1564 .collect::<HashMap<_,_>>();
1565 assert_eq!(lookup, group_map_lookup);
1566
1567 for m in 0..modulo {
1568 assert_eq!(
1569 lookup.get(&m).copied(),
1570 a.iter()
1571 .map(|&b| u64::from(b))
1572 .filter(|&val| val % modulo == m)
1573 .fold(None, |acc, val| {
1574 if val % (modulo - 1) == 0 {
1575 None
1576 } else {
1577 Some(acc.unwrap_or(0) + val)
1578 }
1579 })
1580 );
1581 }
1582 }
1583
1584 fn correct_grouping_map_by_fold_with_modulo_key(a: Vec<u8>, modulo: u8) -> () {
1585 #[derive(Debug, Default, PartialEq)]
1586 struct Accumulator {
1587 acc: u64,
1588 }
1589
1590 let modulo = u64::from(if modulo == 0 { 1 } else { modulo }); // Avoid `% 0`
1591 let lookup = a.iter().map(|&b| u64::from(b)) // Avoid overflows
1592 .into_grouping_map_by(|i| i % modulo)
1593 .fold_with(|_key, _val| Default::default(), |Accumulator { acc }, &key, val| {
1594 assert!(val % modulo == key);
1595 let acc = acc + val;
1596 Accumulator { acc }
1597 });
1598
1599 let group_map_lookup = a.iter()
1600 .map(|&b| u64::from(b))
1601 .map(|i| (i % modulo, i))
1602 .into_group_map()
1603 .into_iter()
1604 .map(|(key, vals)| (key, vals.into_iter().sum())).map(|(key, acc)| (key,Accumulator { acc }))
1605 .collect::<HashMap<_,_>>();
1606 assert_eq!(lookup, group_map_lookup);
1607
1608 for (&key, &Accumulator { acc: sum }) in lookup.iter() {
1609 assert_eq!(sum, a.iter().map(|&b| u64::from(b)).filter(|&val| val % modulo == key).sum::<u64>());
1610 }
1611 }
1612
1613 fn correct_grouping_map_by_fold_modulo_key(a: Vec<u8>, modulo: u8) -> () {
1614 let modulo = u64::from(if modulo == 0 { 1 } else { modulo }); // Avoid `% 0`
1615 let lookup = a.iter().map(|&b| u64::from(b)) // Avoid overflows
1616 .into_grouping_map_by(|i| i % modulo)
1617 .fold(0u64, |acc, &key, val| {
1618 assert!(val % modulo == key);
1619 acc + val
1620 });
1621
1622 let group_map_lookup = a.iter()
1623 .map(|&b| u64::from(b))
1624 .map(|i| (i % modulo, i))
1625 .into_group_map()
1626 .into_iter()
1627 .map(|(key, vals)| (key, vals.into_iter().sum()))
1628 .collect::<HashMap<_,_>>();
1629 assert_eq!(lookup, group_map_lookup);
1630
1631 for (&key, &sum) in lookup.iter() {
1632 assert_eq!(sum, a.iter().map(|&b| u64::from(b)).filter(|&val| val % modulo == key).sum::<u64>());
1633 }
1634 }
1635
1636 fn correct_grouping_map_by_reduce_modulo_key(a: Vec<u8>, modulo: u8) -> () {
1637 let modulo = u64::from(if modulo == 0 { 1 } else { modulo }); // Avoid `% 0`
1638 let lookup = a.iter().map(|&b| u64::from(b)) // Avoid overflows
1639 .into_grouping_map_by(|i| i % modulo)
1640 .reduce(|acc, &key, val| {
1641 assert!(val % modulo == key);
1642 acc + val
1643 });
1644
1645 let group_map_lookup = a.iter()
1646 .map(|&b| u64::from(b))
1647 .map(|i| (i % modulo, i))
1648 .into_group_map()
1649 .into_iter()
1650 .map(|(key, vals)| (key, vals.into_iter().reduce(|acc, val| acc + val).unwrap()))
1651 .collect::<HashMap<_,_>>();
1652 assert_eq!(lookup, group_map_lookup);
1653
1654 for (&key, &sum) in lookup.iter() {
1655 assert_eq!(sum, a.iter().map(|&b| u64::from(b)).filter(|&val| val % modulo == key).sum::<u64>());
1656 }
1657 }
1658
1659 fn correct_grouping_map_by_collect_modulo_key(a: Vec<u8>, modulo: u8) -> () {
1660 let modulo = if modulo == 0 { 1 } else { modulo }; // Avoid `% 0`
1661 let lookup_grouping_map = a.iter().copied().into_grouping_map_by(|i| i % modulo).collect::<Vec<_>>();
1662 let lookup_group_map = a.iter().copied().map(|i| (i % modulo, i)).into_group_map();
1663
1664 assert_eq!(lookup_grouping_map, lookup_group_map);
1665 }
1666
1667 fn correct_grouping_map_by_max_modulo_key(a: Vec<u8>, modulo: u8) -> () {
1668 let modulo = if modulo == 0 { 1 } else { modulo }; // Avoid `% 0`
1669 let lookup = a.iter().copied().into_grouping_map_by(|i| i % modulo).max();
1670
1671 let group_map_lookup = a.iter().copied()
1672 .map(|i| (i % modulo, i))
1673 .into_group_map()
1674 .into_iter()
1675 .map(|(key, vals)| (key, vals.into_iter().max().unwrap()))
1676 .collect::<HashMap<_,_>>();
1677 assert_eq!(lookup, group_map_lookup);
1678
1679 for (&key, &max) in lookup.iter() {
1680 assert_eq!(Some(max), a.iter().copied().filter(|&val| val % modulo == key).max());
1681 }
1682 }
1683
1684 fn correct_grouping_map_by_max_by_modulo_key(a: Vec<u8>, modulo: u8) -> () {
1685 let modulo = if modulo == 0 { 1 } else { modulo }; // Avoid `% 0`
1686 let lookup = a.iter().copied().into_grouping_map_by(|i| i % modulo).max_by(|_, v1, v2| v1.cmp(v2));
1687
1688 let group_map_lookup = a.iter().copied()
1689 .map(|i| (i % modulo, i))
1690 .into_group_map()
1691 .into_iter()
1692 .map(|(key, vals)| (key, vals.into_iter().max_by(|v1, v2| v1.cmp(v2)).unwrap()))
1693 .collect::<HashMap<_,_>>();
1694 assert_eq!(lookup, group_map_lookup);
1695
1696 for (&key, &max) in lookup.iter() {
1697 assert_eq!(Some(max), a.iter().copied().filter(|&val| val % modulo == key).max_by(|v1, v2| v1.cmp(v2)));
1698 }
1699 }
1700
1701 fn correct_grouping_map_by_max_by_key_modulo_key(a: Vec<u8>, modulo: u8) -> () {
1702 let modulo = if modulo == 0 { 1 } else { modulo }; // Avoid `% 0`
1703 let lookup = a.iter().copied().into_grouping_map_by(|i| i % modulo).max_by_key(|_, &val| val);
1704
1705 let group_map_lookup = a.iter().copied()
1706 .map(|i| (i % modulo, i))
1707 .into_group_map()
1708 .into_iter()
1709 .map(|(key, vals)| (key, vals.into_iter().max_by_key(|&val| val).unwrap()))
1710 .collect::<HashMap<_,_>>();
1711 assert_eq!(lookup, group_map_lookup);
1712
1713 for (&key, &max) in lookup.iter() {
1714 assert_eq!(Some(max), a.iter().copied().filter(|&val| val % modulo == key).max_by_key(|&val| val));
1715 }
1716 }
1717
1718 fn correct_grouping_map_by_min_modulo_key(a: Vec<u8>, modulo: u8) -> () {
1719 let modulo = if modulo == 0 { 1 } else { modulo }; // Avoid `% 0`
1720 let lookup = a.iter().copied().into_grouping_map_by(|i| i % modulo).min();
1721
1722 let group_map_lookup = a.iter().copied()
1723 .map(|i| (i % modulo, i))
1724 .into_group_map()
1725 .into_iter()
1726 .map(|(key, vals)| (key, vals.into_iter().min().unwrap()))
1727 .collect::<HashMap<_,_>>();
1728 assert_eq!(lookup, group_map_lookup);
1729
1730 for (&key, &min) in lookup.iter() {
1731 assert_eq!(Some(min), a.iter().copied().filter(|&val| val % modulo == key).min());
1732 }
1733 }
1734
1735 fn correct_grouping_map_by_min_by_modulo_key(a: Vec<u8>, modulo: u8) -> () {
1736 let modulo = if modulo == 0 { 1 } else { modulo }; // Avoid `% 0`
1737 let lookup = a.iter().copied().into_grouping_map_by(|i| i % modulo).min_by(|_, v1, v2| v1.cmp(v2));
1738
1739 let group_map_lookup = a.iter().copied()
1740 .map(|i| (i % modulo, i))
1741 .into_group_map()
1742 .into_iter()
1743 .map(|(key, vals)| (key, vals.into_iter().min_by(|v1, v2| v1.cmp(v2)).unwrap()))
1744 .collect::<HashMap<_,_>>();
1745 assert_eq!(lookup, group_map_lookup);
1746
1747 for (&key, &min) in lookup.iter() {
1748 assert_eq!(Some(min), a.iter().copied().filter(|&val| val % modulo == key).min_by(|v1, v2| v1.cmp(v2)));
1749 }
1750 }
1751
1752 fn correct_grouping_map_by_min_by_key_modulo_key(a: Vec<u8>, modulo: u8) -> () {
1753 let modulo = if modulo == 0 { 1 } else { modulo }; // Avoid `% 0`
1754 let lookup = a.iter().copied().into_grouping_map_by(|i| i % modulo).min_by_key(|_, &val| val);
1755
1756 let group_map_lookup = a.iter().copied()
1757 .map(|i| (i % modulo, i))
1758 .into_group_map()
1759 .into_iter()
1760 .map(|(key, vals)| (key, vals.into_iter().min_by_key(|&val| val).unwrap()))
1761 .collect::<HashMap<_,_>>();
1762 assert_eq!(lookup, group_map_lookup);
1763
1764 for (&key, &min) in lookup.iter() {
1765 assert_eq!(Some(min), a.iter().copied().filter(|&val| val % modulo == key).min_by_key(|&val| val));
1766 }
1767 }
1768
1769 fn correct_grouping_map_by_minmax_modulo_key(a: Vec<u8>, modulo: u8) -> () {
1770 let modulo = if modulo == 0 { 1 } else { modulo }; // Avoid `% 0`
1771 let lookup = a.iter().copied().into_grouping_map_by(|i| i % modulo).minmax();
1772
1773 let group_map_lookup = a.iter().copied()
1774 .map(|i| (i % modulo, i))
1775 .into_group_map()
1776 .into_iter()
1777 .map(|(key, vals)| (key, vals.into_iter().minmax()))
1778 .collect::<HashMap<_,_>>();
1779 assert_eq!(lookup, group_map_lookup);
1780
1781 for (&key, &minmax) in lookup.iter() {
1782 assert_eq!(minmax, a.iter().copied().filter(|&val| val % modulo == key).minmax());
1783 }
1784 }
1785
1786 fn correct_grouping_map_by_minmax_by_modulo_key(a: Vec<u8>, modulo: u8) -> () {
1787 let modulo = if modulo == 0 { 1 } else { modulo }; // Avoid `% 0`
1788 let lookup = a.iter().copied().into_grouping_map_by(|i| i % modulo).minmax_by(|_, v1, v2| v1.cmp(v2));
1789
1790 let group_map_lookup = a.iter().copied()
1791 .map(|i| (i % modulo, i))
1792 .into_group_map()
1793 .into_iter()
1794 .map(|(key, vals)| (key, vals.into_iter().minmax_by(|v1, v2| v1.cmp(v2))))
1795 .collect::<HashMap<_,_>>();
1796 assert_eq!(lookup, group_map_lookup);
1797
1798 for (&key, &minmax) in lookup.iter() {
1799 assert_eq!(minmax, a.iter().copied().filter(|&val| val % modulo == key).minmax_by(|v1, v2| v1.cmp(v2)));
1800 }
1801 }
1802
1803 fn correct_grouping_map_by_minmax_by_key_modulo_key(a: Vec<u8>, modulo: u8) -> () {
1804 let modulo = if modulo == 0 { 1 } else { modulo }; // Avoid `% 0`
1805 let lookup = a.iter().copied().into_grouping_map_by(|i| i % modulo).minmax_by_key(|_, &val| val);
1806
1807 let group_map_lookup = a.iter().copied()
1808 .map(|i| (i % modulo, i))
1809 .into_group_map()
1810 .into_iter()
1811 .map(|(key, vals)| (key, vals.into_iter().minmax_by_key(|&val| val)))
1812 .collect::<HashMap<_,_>>();
1813 assert_eq!(lookup, group_map_lookup);
1814
1815 for (&key, &minmax) in lookup.iter() {
1816 assert_eq!(minmax, a.iter().copied().filter(|&val| val % modulo == key).minmax_by_key(|&val| val));
1817 }
1818 }
1819
1820 fn correct_grouping_map_by_sum_modulo_key(a: Vec<u8>, modulo: u8) -> () {
1821 let modulo = u64::from(if modulo == 0 { 1 } else { modulo }); // Avoid `% 0`
1822 let lookup = a.iter().map(|&b| u64::from(b)) // Avoid overflows
1823 .into_grouping_map_by(|i| i % modulo)
1824 .sum();
1825
1826 let group_map_lookup = a.iter().map(|&b| u64::from(b))
1827 .map(|i| (i % modulo, i))
1828 .into_group_map()
1829 .into_iter()
1830 .map(|(key, vals)| (key, vals.into_iter().sum()))
1831 .collect::<HashMap<_,_>>();
1832 assert_eq!(lookup, group_map_lookup);
1833
1834 for (&key, &sum) in lookup.iter() {
1835 assert_eq!(sum, a.iter().map(|&b| u64::from(b)).filter(|&val| val % modulo == key).sum::<u64>());
1836 }
1837 }
1838
1839 fn correct_grouping_map_by_product_modulo_key(a: Vec<u8>, modulo: u8) -> () {
1840 let modulo = Wrapping(u64::from(if modulo == 0 { 1 } else { modulo })); // Avoid `% 0`
1841 let lookup = a.iter().map(|&b| Wrapping(u64::from(b))) // Avoid overflows
1842 .into_grouping_map_by(|i| i % modulo)
1843 .product();
1844
1845 let group_map_lookup = a.iter().map(|&b| Wrapping(u64::from(b)))
1846 .map(|i| (i % modulo, i))
1847 .into_group_map()
1848 .into_iter()
1849 .map(|(key, vals)| (key, vals.into_iter().product::<Wrapping<u64>>()))
1850 .collect::<HashMap<_,_>>();
1851 assert_eq!(lookup, group_map_lookup);
1852
1853 for (&key, &prod) in lookup.iter() {
1854 assert_eq!(
1855 prod,
1856 a.iter()
1857 .map(|&b| Wrapping(u64::from(b)))
1858 .filter(|&val| val % modulo == key)
1859 .product::<Wrapping<u64>>()
1860 );
1861 }
1862 }
1863
1864 // This should check that if multiple elements are equally minimum or maximum
1865 // then `max`, `min` and `minmax` pick the first minimum and the last maximum.
1866 // This is to be consistent with `std::iter::max` and `std::iter::min`.
1867 fn correct_grouping_map_by_min_max_minmax_order_modulo_key() -> () {
1868 use itertools::MinMaxResult;
1869
1870 let lookup = (0..=10)
1871 .into_grouping_map_by(|_| 0)
1872 .max_by(|_, _, _| Ordering::Equal);
1873
1874 assert_eq!(lookup[&0], 10);
1875
1876 let lookup = (0..=10)
1877 .into_grouping_map_by(|_| 0)
1878 .min_by(|_, _, _| Ordering::Equal);
1879
1880 assert_eq!(lookup[&0], 0);
1881
1882 let lookup = (0..=10)
1883 .into_grouping_map_by(|_| 0)
1884 .minmax_by(|_, _, _| Ordering::Equal);
1885
1886 assert_eq!(lookup[&0], MinMaxResult::MinMax(0, 10));
1887 }
1888 }
1889
1890 quickcheck! {
1891 fn counts(nums: Vec<isize>) -> TestResult {
1892 let counts = nums.iter().counts();
1893 for (&item, &count) in counts.iter() {
1894 #[allow(clippy::absurd_extreme_comparisons)]
1895 if count <= 0 {
1896 return TestResult::failed();
1897 }
1898 if count != nums.iter().filter(|&x| x == item).count() {
1899 return TestResult::failed();
1900 }
1901 }
1902 for item in nums.iter() {
1903 if !counts.contains_key(item) {
1904 return TestResult::failed();
1905 }
1906 }
1907 TestResult::passed()
1908 }
1909 }
1910
1911 quickcheck! {
1912 fn test_double_ended_zip_2(a: Vec<u8>, b: Vec<u8>) -> TestResult {
1913 let mut x =
1914 multizip((a.clone().into_iter(), b.clone().into_iter()))
1915 .collect_vec();
1916 x.reverse();
1917
1918 let y =
1919 multizip((a.into_iter(), b.into_iter()))
1920 .rfold(Vec::new(), |mut vec, e| { vec.push(e); vec });
1921
1922 TestResult::from_bool(itertools::equal(x, y))
1923 }
1924
1925 fn test_double_ended_zip_3(a: Vec<u8>, b: Vec<u8>, c: Vec<u8>) -> TestResult {
1926 let mut x =
1927 multizip((a.clone().into_iter(), b.clone().into_iter(), c.clone().into_iter()))
1928 .collect_vec();
1929 x.reverse();
1930
1931 let y =
1932 multizip((a.into_iter(), b.into_iter(), c.into_iter()))
1933 .rfold(Vec::new(), |mut vec, e| { vec.push(e); vec });
1934
1935 TestResult::from_bool(itertools::equal(x, y))
1936 }
1937 }
1938
1939 fn is_fused<I: Iterator>(mut it: I) -> bool {
1940 for _ in it.by_ref() {}
1941 for _ in 0..10 {
1942 if it.next().is_some() {
1943 return false;
1944 }
1945 }
1946 true
1947 }
1948
1949 quickcheck! {
1950 fn fused_combination(a: Iter<i16>) -> bool
1951 {
1952 is_fused(a.clone().combinations(1)) &&
1953 is_fused(a.combinations(3))
1954 }
1955
1956 fn fused_combination_with_replacement(a: Iter<i16>) -> bool
1957 {
1958 is_fused(a.clone().combinations_with_replacement(1)) &&
1959 is_fused(a.combinations_with_replacement(3))
1960 }
1961
1962 fn fused_array_combination_with_replacement(a: Iter<i16>) -> bool
1963 {
1964 is_fused(a.clone().array_combinations_with_replacement::<1>()) &&
1965 is_fused(a.array_combinations_with_replacement::<3>())
1966 }
1967 fn fused_tuple_combination(a: Iter<i16>) -> bool
1968 {
1969 is_fused(a.clone().fuse().tuple_combinations::<(_,)>()) &&
1970 is_fused(a.fuse().tuple_combinations::<(_,_,_)>())
1971 }
1972
1973 fn fused_unique(a: Iter<i16>) -> bool
1974 {
1975 is_fused(a.fuse().unique())
1976 }
1977
1978 fn fused_unique_by(a: Iter<i16>) -> bool
1979 {
1980 is_fused(a.fuse().unique_by(|x| x % 100))
1981 }
1982
1983 fn fused_interleave_shortest(a: Iter<i16>, b: Iter<i16>) -> bool
1984 {
1985 !is_fused(a.clone().interleave_shortest(b.clone())) &&
1986 is_fused(a.fuse().interleave_shortest(b.fuse()))
1987 }
1988
1989 fn fused_product(a: Iter<i16>, b: Iter<i16>) -> bool
1990 {
1991 is_fused(a.fuse().cartesian_product(b.fuse()))
1992 }
1993
1994 fn fused_merge(a: Iter<i16>, b: Iter<i16>) -> bool
1995 {
1996 is_fused(a.fuse().merge(b.fuse()))
1997 }
1998
1999 fn fused_filter_ok(a: Iter<i16>) -> bool
2000 {
2001 is_fused(a.map(|x| if x % 2 == 0 {Ok(x)} else {Err(x)} )
2002 .filter_ok(|x| x % 3 == 0)
2003 .fuse())
2004 }
2005
2006 fn fused_filter_map_ok(a: Iter<i16>) -> bool
2007 {
2008 is_fused(a.map(|x| if x % 2 == 0 {Ok(x)} else {Err(x)} )
2009 .filter_map_ok(|x| if x % 3 == 0 {Some(x / 3)} else {None})
2010 .fuse())
2011 }
2012
2013 fn fused_positions(a: Iter<i16>) -> bool
2014 {
2015 !is_fused(a.clone().positions(|x|x%2==0)) &&
2016 is_fused(a.fuse().positions(|x|x%2==0))
2017 }
2018
2019 fn fused_update(a: Iter<i16>) -> bool
2020 {
2021 !is_fused(a.clone().update(|x|*x+=1)) &&
2022 is_fused(a.fuse().update(|x|*x+=1))
2023 }
2024
2025 fn fused_tuple_windows(a: Iter<i16>) -> bool
2026 {
2027 is_fused(a.fuse().tuple_windows::<(_,_)>())
2028 }
2029
2030 fn fused_pad_using(a: Iter<i16>) -> bool
2031 {
2032 is_fused(a.fuse().pad_using(100,|_|0))
2033 }
2034 }
2035
2036 quickcheck! {
2037 fn min_set_contains_min(a: Vec<(usize, char)>) -> bool {
2038 let result_set = a.iter().min_set();
2039 if let Some(result_element) = a.iter().min() {
2040 result_set.contains(&result_element)
2041 } else {
2042 result_set.is_empty()
2043 }
2044 }
2045
2046 fn min_set_by_contains_min(a: Vec<(usize, char)>) -> bool {
2047 let compare = |x: &&(usize, char), y: &&(usize, char)| x.1.cmp(&y.1);
2048 let result_set = a.iter().min_set_by(compare);
2049 if let Some(result_element) = a.iter().min_by(compare) {
2050 result_set.contains(&result_element)
2051 } else {
2052 result_set.is_empty()
2053 }
2054 }
2055
2056 fn min_set_by_key_contains_min(a: Vec<(usize, char)>) -> bool {
2057 let key = |x: &&(usize, char)| x.1;
2058 let result_set = a.iter().min_set_by_key(&key);
2059 if let Some(result_element) = a.iter().min_by_key(&key) {
2060 result_set.contains(&result_element)
2061 } else {
2062 result_set.is_empty()
2063 }
2064 }
2065
2066 fn max_set_contains_max(a: Vec<(usize, char)>) -> bool {
2067 let result_set = a.iter().max_set();
2068 if let Some(result_element) = a.iter().max() {
2069 result_set.contains(&result_element)
2070 } else {
2071 result_set.is_empty()
2072 }
2073 }
2074
2075 fn max_set_by_contains_max(a: Vec<(usize, char)>) -> bool {
2076 let compare = |x: &&(usize, char), y: &&(usize, char)| x.1.cmp(&y.1);
2077 let result_set = a.iter().max_set_by(compare);
2078 if let Some(result_element) = a.iter().max_by(compare) {
2079 result_set.contains(&result_element)
2080 } else {
2081 result_set.is_empty()
2082 }
2083 }
2084
2085 fn max_set_by_key_contains_max(a: Vec<(usize, char)>) -> bool {
2086 let key = |x: &&(usize, char)| x.1;
2087 let result_set = a.iter().max_set_by_key(&key);
2088 if let Some(result_element) = a.iter().max_by_key(&key) {
2089 result_set.contains(&result_element)
2090 } else {
2091 result_set.is_empty()
2092 }
2093 }
2094
2095 fn tail(v: Vec<i32>, n: u8) -> bool {
2096 let n = n as usize;
2097 let result = &v[v.len().saturating_sub(n)..];
2098 itertools::equal(v.iter().tail(n), result)
2099 && itertools::equal(v.iter().filter(|_| true).tail(n), result)
2100 }
2101
2102 fn strip_prefix_matches_str(haystack: String, needle: String) -> bool {
2103 let expected = haystack.strip_prefix(&needle);
2104 let got: Option<String> = haystack
2105 .chars()
2106 .strip_prefix(needle.chars())
2107 .ok()
2108 .map(Iterator::collect);
2109 got.as_deref() == expected
2110 }
2111
2112 fn strip_prefix_by_matches_strip_prefix(v: Vec<i32>, n: u8) -> bool {
2113 let prefix: Vec<i32> = v.iter().take(n as usize).copied().collect();
2114 let by_eq = v.iter().strip_prefix_by(&prefix, |a, b| **a == **b).ok();
2115 let plain = v.iter().strip_prefix(prefix.iter()).ok();
2116 match (by_eq, plain) {
2117 (Some(a), Some(b)) => itertools::equal(a, b),
2118 (None, None) => true,
2119 _ => false,
2120 }
2121 }
2122 }
2123
2124 #[test]
2125 fn strip_prefix_error_exposes_mismatch_and_remainders() {
2126 let err = (1..6)
2127 .strip_prefix([1, 2, 9, 4])
2128 .expect_err("third item mismatches");
2129 assert_eq!(err.mismatch, (Some(3), 9));
2130 assert_eq!(err.prefix.collect_vec(), vec![4]);
2131 assert_eq!(err.iterator.collect_vec(), vec![4, 5]);
2132 }
2133
2134 #[test]
2135 fn strip_prefix_error_signals_self_exhausted() {
2136 let err = (1..3).strip_prefix([1, 2, 3]).expect_err("self exhausted");
2137 assert_eq!(err.mismatch, (None, 3));
2138 assert!(err.iterator.collect_vec().is_empty());
2139 }