//! implementation of the sorted_iterator set operations use super::*; use core::cmp::Ordering::*; use core::cmp::{max, min, Ordering, Reverse}; use core::iter::Peekable; use core::{iter, ops, option, result}; use std::collections; use std::collections::BinaryHeap; use std::iter::FusedIterator; /// marker trait for iterators that are sorted by their Item pub trait SortedByItem {} pub struct Union { pub(crate) a: Peekable, pub(crate) b: Peekable, } impl Clone for Union where I::Item: Clone, J::Item: Clone, { fn clone(&self) -> Self { Self { a: self.a.clone(), b: self.b.clone(), } } } impl, J: Iterator> Iterator for Union { type Item = K; fn next(&mut self) -> Option { if let (Some(ak), Some(bk)) = (self.a.peek(), self.b.peek()) { match ak.cmp(&bk) { Less => self.a.next(), Greater => self.b.next(), Equal => { self.b.next(); self.a.next() } } } else { self.a.next().or_else(|| self.b.next()) } } fn size_hint(&self) -> (usize, Option) { let (amin, amax) = self.a.size_hint(); let (bmin, bmax) = self.b.size_hint(); // full overlap let rmin = max(amin, bmin); // no overlap let rmax = amax.and_then(|amax| bmax.and_then(|bmax| amax.checked_add(bmax))); (rmin, rmax) } } // An iterator with the first item pulled out. pub(crate) struct Peeked { h: Reverse, t: I, } impl Peeked { fn new(mut i: I) -> Option> { i.next().map(|x| Peeked { h: Reverse(x), t: i, }) } fn size_hint(&self) -> (usize, Option) { let (lo, hi) = self.t.size_hint(); (lo + 1, hi.map(|hi| hi + 1)) } } // Delegate comparisons to the head element. impl PartialEq for Peeked where I::Item: PartialEq, { fn eq(&self, that: &Self) -> bool { self.h.eq(&that.h) } } impl Eq for Peeked where I::Item: Eq {} impl PartialOrd for Peeked where I::Item: PartialOrd, { fn partial_cmp(&self, that: &Self) -> Option { self.h.partial_cmp(&that.h) } } impl Ord for Peeked where I::Item: Ord, { fn cmp(&self, that: &Self) -> core::cmp::Ordering { self.h.cmp(&that.h) } } impl Clone for Peeked where I::Item: Clone, { fn clone(&self) -> Self { Self { h: self.h.clone(), t: self.t.clone(), } } } pub struct MultiwayUnion { pub(crate) bh: BinaryHeap>, } impl MultiwayUnion where I::Item: Ord, { pub(crate) fn from_iter>(x: T) -> MultiwayUnion { MultiwayUnion { bh: x.into_iter().filter_map(Peeked::new).collect(), } } } impl Clone for MultiwayUnion where I::Item: Clone, { fn clone(&self) -> Self { Self { bh: self.bh.clone(), } } } impl Iterator for MultiwayUnion where I::Item: Ord, { type Item = I::Item; fn next(&mut self) -> Option { // Extract the current minimum element. self.bh.pop().map( |Peeked { h: Reverse(item), t: top_tail, }| { // Advance the iterator and re-insert it into the heap. Peeked::new(top_tail).map(|i| self.bh.push(i)); // Remove equivalent elements and advance corresponding iterators. while self.bh.peek().filter(|x| x.h.0 == item).is_some() { let tail = self.bh.pop().unwrap().t; Peeked::new(tail).map(|i| self.bh.push(i)); } item }, ) } fn size_hint(&self) -> (usize, Option) { self.bh.iter().fold((0, Some(0)), |(lo, hi), it| { let (ilo, ihi) = it.size_hint(); ( max(lo, ilo), hi.and_then(|hi| ihi.and_then(|ihi| hi.checked_add(ihi))), ) }) } } pub struct Intersection { pub(crate) a: I, pub(crate) b: Peekable, } impl Clone for Intersection where I::Item: Clone, J::Item: Clone, { fn clone(&self) -> Self { Self { a: self.a.clone(), b: self.b.clone(), } } } impl, J: Iterator> Iterator for Intersection { type Item = K; fn next(&mut self) -> Option { while let Some(a) = self.a.next() { while let Some(b) = self.b.peek() { let order = a.cmp(b); if order == Less { break; } self.b.next(); if order == Equal { return Some(a); } } } None } fn size_hint(&self) -> (usize, Option) { let (_, amax) = self.a.size_hint(); let (_, bmax) = self.b.size_hint(); // no overlap let rmin = 0; // full overlap let rmax = amax.and_then(|amax| bmax.map(|bmax| min(amax, bmax))); (rmin, rmax) } } pub struct Difference { pub(crate) a: I, pub(crate) b: Peekable, } impl Clone for Difference where I::Item: Clone, J::Item: Clone, { fn clone(&self) -> Self { Self { a: self.a.clone(), b: self.b.clone(), } } } impl, J: Iterator> Iterator for Difference { type Item = K; fn next(&mut self) -> Option { 'next_a: while let Some(a) = self.a.next() { while let Some(b) = self.b.peek() { let order = a.cmp(b); if order == Less { break; } self.b.next(); if order == Equal { continue 'next_a; } } return Some(a); } None } fn size_hint(&self) -> (usize, Option) { let (amin, amax) = self.a.size_hint(); let (_, bmax) = self.b.size_hint(); // no overlap let rmax = amax; // if the other has at most bmax elements, and we have at least amin elements let rmin = bmax.map_or(0, |bmax| amin.saturating_sub(bmax)); (rmin, rmax) } } pub struct SymmetricDifference { pub(crate) a: Peekable, pub(crate) b: Peekable, } impl Clone for SymmetricDifference where I::Item: Clone, J::Item: Clone, { fn clone(&self) -> Self { Self { a: self.a.clone(), b: self.b.clone(), } } } impl, J: Iterator> Iterator for SymmetricDifference { type Item = K; fn next(&mut self) -> Option { while let (Some(ak), Some(bk)) = (self.a.peek(), self.b.peek()) { match ak.cmp(&bk) { Less => return self.a.next(), Greater => return self.b.next(), Equal => { self.b.next(); self.a.next(); } } } self.a.next().or_else(|| self.b.next()) } fn size_hint(&self) -> (usize, Option) { let (amin, amax) = self.a.size_hint(); let (bmin, bmax) = self.b.size_hint(); // full overlap let rmin = match (amax, bmax) { (Some(amax), _) if bmin >= amax => bmin - amax, (_, Some(bmax)) if amin >= bmax => amin - bmax, _ => 0, }; // no overlap let rmax = amax.and_then(|amax| bmax.and_then(|bmax| amax.checked_add(bmax))); (rmin, rmax) } } #[derive(Clone, Debug)] pub struct Pairs { pub(crate) i: I, } impl Iterator for Pairs { type Item = (I::Item, ()); fn next(&mut self) -> Option { self.i.next().map(|k| (k, ())) } fn size_hint(&self) -> (usize, Option) { self.i.size_hint() } } #[derive(Clone, Debug)] pub struct AssumeSortedByItem { pub(crate) i: I, } impl Iterator for AssumeSortedByItem { type Item = I::Item; fn next(&mut self) -> Option { self.i.next() } fn size_hint(&self) -> (usize, Option) { self.i.size_hint() } } impl ExactSizeIterator for AssumeSortedByItem where I: ExactSizeIterator {} impl FusedIterator for AssumeSortedByItem where I: FusedIterator {} impl DoubleEndedIterator for AssumeSortedByItem where I: DoubleEndedIterator { fn next_back(&mut self) -> Option { self.i.next_back() } } // mark common std traits impl SortedByItem for iter::Empty {} impl SortedByItem for iter::Once {} impl<'a, T> SortedByItem for option::Iter<'a, T> {} impl<'a, T> SortedByItem for result::Iter<'a, T> {} impl SortedByItem for option::IntoIter {} impl SortedByItem for result::IntoIter {} impl SortedByItem for iter::Take {} impl SortedByItem for iter::Skip {} impl SortedByItem for iter::StepBy {} impl SortedByItem for iter::Cloned {} impl SortedByItem for iter::Copied {} impl SortedByItem for iter::Fuse {} impl SortedByItem for iter::Inspect {} impl SortedByItem for iter::TakeWhile {} impl SortedByItem for iter::SkipWhile {} impl SortedByItem for iter::Filter {} impl SortedByItem for iter::Peekable {} impl SortedByItem for collections::btree_set::IntoIter {} impl<'a, T> SortedByItem for collections::btree_set::Iter<'a, T> {} impl<'a, T> SortedByItem for collections::btree_set::Intersection<'a, T> {} impl<'a, T> SortedByItem for collections::btree_set::Union<'a, T> {} impl<'a, T> SortedByItem for collections::btree_set::Difference<'a, T> {} impl<'a, T> SortedByItem for collections::btree_set::SymmetricDifference<'a, T> {} impl<'a, T> SortedByItem for collections::btree_set::Range<'a, T> {} impl<'a, K, V> SortedByItem for collections::btree_map::Keys<'a, K, V> {} impl SortedByItem for ops::Range {} impl SortedByItem for ops::RangeInclusive {} impl SortedByItem for ops::RangeFrom {} impl SortedByItem for Keys {} impl SortedByItem for AssumeSortedByItem {} impl SortedByItem for Union {} impl SortedByItem for Intersection {} impl SortedByItem for Difference {} impl SortedByItem for SymmetricDifference {} impl SortedByItem for MultiwayUnion {} impl SortedByItem for Box {} impl SortedByItem for iter::Map {} impl SortedByItem for iter::FlatMap where Iin: OneOrLess, J: IntoIterator, Iout: SortedByItem, { } impl SortedByItem for iter::Flatten where Iin: OneOrLess + Iterator, J: IntoIterator, Iout: SortedByItem, { } #[cfg(test)] mod tests { use super::*; use core::fmt::Debug; use std::collections::BTreeMap; /// just a helper to get good output when a check fails fn binary_op(a: E, b: E, expected: R, actual: R) -> bool { let res = expected == actual; if !res { println!( "a:{:?} b:{:?} expected:{:?} actual:{:?}", a, b, expected, actual ); } res } type Element = i64; type Reference = collections::BTreeSet; #[quickcheck] fn intersection(a: Reference, b: Reference) -> bool { let expected: Reference = a.intersection(&b).cloned().collect(); let actual: Reference = a .clone() .into_iter() .intersection(b.clone().into_iter()) .collect(); binary_op(a, b, expected, actual) } #[quickcheck] fn union(a: Reference, b: Reference) -> bool { let expected: Reference = a.union(&b).cloned().collect(); let actual: Reference = a.clone().into_iter().union(b.clone().into_iter()).collect(); binary_op(a, b, expected, actual) } #[quickcheck] fn multi_union(inputs: Vec) -> bool { let expected: Reference = inputs.iter().flatten().copied().collect(); let actual = MultiwayUnion::from_iter(inputs.iter().map(|i| i.iter())); let res = actual.clone().eq(expected.iter()); if !res { let actual: Reference = actual.copied().collect(); println!("in:{:?} expected:{:?} out:{:?}", inputs, expected, actual); } res } #[quickcheck] fn difference(a: Reference, b: Reference) -> bool { let expected: Reference = a.difference(&b).cloned().collect(); let actual: Reference = a .clone() .into_iter() .difference(b.clone().into_iter()) .collect(); binary_op(a, b, expected, actual) } #[quickcheck] fn symmetric_difference(a: Reference, b: Reference) -> bool { let expected: Reference = a.symmetric_difference(&b).cloned().collect(); let actual: Reference = a .clone() .into_iter() .symmetric_difference(b.clone().into_iter()) .collect(); binary_op(a, b, expected, actual) } /// just a helper to get good output when a check fails fn check_size_hint( input: E, expected: usize, (min, max): (usize, Option), ) -> bool { let res = min <= expected && max.map_or(true, |max| expected <= max && min <= max); if !res { println!( "input:{:?} expected:{:?} min:{:?} max:{:?}", input, expected, min, max ); } res } #[quickcheck] fn intersection_size_hint(a: Reference, b: Reference) -> bool { let expected = a.intersection(&b).count(); let actual = a.iter().intersection(b.iter()).size_hint(); check_size_hint((a, b), expected, actual) } #[quickcheck] fn union_size_hint(a: Reference, b: Reference) -> bool { let expected = a.union(&b).count(); let actual = a.iter().union(b.iter()).size_hint(); check_size_hint((a, b), expected, actual) } #[quickcheck] fn multi_union_size_hint(inputs: Vec) -> bool { let expected: Reference = inputs.iter().flatten().copied().collect(); let actual = MultiwayUnion::from_iter(inputs.iter().map(|i| i.iter())).size_hint(); check_size_hint(inputs, expected.len(), actual) } #[quickcheck] fn difference_size_hint(a: Reference, b: Reference) -> bool { let expected = a.difference(&b).count(); let actual = a.iter().difference(b.iter()).size_hint(); check_size_hint((a, b), expected, actual) } #[quickcheck] fn symmetric_difference_size_hint(a: Reference, b: Reference) -> bool { let expected = a.symmetric_difference(&b).count(); let actual = a.iter().symmetric_difference(b.iter()).size_hint(); check_size_hint((a, b), expected, actual) } fn s() -> impl Iterator + SortedByItem { 0i64..10 } fn r<'a>() -> impl Iterator + SortedByItem { iter::empty() } fn is_s + SortedByItem>(_v: I) {} #[test] fn instances() { is_s(iter::empty::()); is_s(iter::once(0u64)); // ranges is_s(0i64..10); is_s(0i64..=10); is_s(0i64..); // wrappers is_s(Box::new(0i64..10)); // identity is_s(s().fuse()); is_s(r().cloned()); is_s(r().copied()); is_s(r().peekable()); is_s(s().inspect(|_| {})); // removing items is_s(s().step_by(2)); is_s(s().take(1)); is_s(s().take_while(|_| true)); is_s(s().skip(1)); is_s(s().skip_while(|_| true)); is_s(s().filter(|_| true)); // set ops is_s(s().union(s())); is_s(s().intersection(s())); is_s(s().difference(s())); is_s(s().symmetric_difference(s())); is_s(multiway_union(vec![s(), s(), s()])); is_s(multiway_union(iter::once(s()))); // one_or_less let a_btree = BTreeMap::::new(); is_s( Some(()) .iter() .map(|_| &a_btree) .filter(|b| !b.is_empty()) .flat_map(|m| m.keys()), ); is_s( iter::once(Some(())) .flatten() .map(|_| &a_btree) .filter(|b| !b.is_empty()) .flat_map(|m| m.keys()), ); } }