//! implementation of the sorted_pair_iterator relational operations use super::*; use crate::sorted_iterator::SortedByItem; use core::{ cmp::Ordering::*, cmp::{max, min}, fmt::Debug, iter, iter::Peekable, option, result, }; use std::{collections, iter::FusedIterator}; /// marker trait for iterators that are sorted by the key of their Item pub trait SortedByKey {} pub struct Join { pub(crate) a: Peekable, pub(crate) b: Peekable, } impl Iterator for Join where K: Ord, I: Iterator + SortedByKey, J: Iterator + SortedByKey, { type Item = (K, (A, B)); fn next(&mut self) -> Option { while let (Some((ak, _)), Some((bk, _))) = (self.a.peek(), self.b.peek()) { match ak.cmp(&bk) { Less => { self.a.next(); } Greater => { self.b.next(); } Equal => { if let (Some((ak, av)), Some((_, bv))) = (self.a.next(), self.b.next()) { return Some((ak, (av, bv))); } else { unreachable!(); } } } } None } fn size_hint(&self) -> (usize, Option) { let (_, amax) = self.a.size_hint(); let (_, bmax) = self.b.size_hint(); let rmin = 0; let rmax = amax.and_then(|amax| bmax.map(|bmax| min(amax, bmax))); (rmin, rmax) } } impl Clone for Join where I::Item: Clone, J::Item: Clone, { fn clone(&self) -> Self { Self { a: self.a.clone(), b: self.b.clone(), } } } pub struct LeftJoin { pub(crate) a: Peekable, pub(crate) b: Peekable, } impl Iterator for LeftJoin where K: Ord, I: Iterator, J: Iterator, { type Item = (K, (A, Option)); fn next(&mut self) -> Option { let (ak, av) = self.a.next()?; while let Some((bk, _)) = self.b.peek() { match ak.cmp(bk) { Less => break, Greater => { self.b.next(); } Equal => { let (_, bv) = self.b.next()?; return Some((ak, (av, Some(bv)))); } } } Some((ak, (av, None))) } fn size_hint(&self) -> (usize, Option) { self.a.size_hint() } } impl Clone for LeftJoin where I::Item: Clone, J::Item: Clone, { fn clone(&self) -> Self { Self { a: self.a.clone(), b: self.b.clone(), } } } pub struct RightJoin { pub(crate) a: Peekable, pub(crate) b: Peekable, } impl Iterator for RightJoin where K: Ord, I: Iterator, J: Iterator, { type Item = (K, (Option, B)); fn next(&mut self) -> Option { let (bk, bv) = self.b.next()?; while let Some((ak, _)) = self.a.peek() { match bk.cmp(ak) { Less => break, Greater => { self.a.next(); } Equal => { let (_, av) = self.a.next()?; return Some((bk, (Some(av), bv))); } } } Some((bk, (None, bv))) } fn size_hint(&self) -> (usize, Option) { self.b.size_hint() } } impl Clone for RightJoin where I::Item: Clone, J::Item: Clone, { fn clone(&self) -> Self { Self { a: self.a.clone(), b: self.b.clone(), } } } pub struct OuterJoin { pub(crate) a: Peekable, pub(crate) b: Peekable, } // all this just so I could avoid having this expression twice in the iterator. // Sometimes making things DRY in rust is hard... impl OuterJoin where K: Ord, I: Iterator, J: Iterator, { // type alias does not help much here... #[allow(clippy::type_complexity)] fn next_a(&mut self) -> Option<(K, (Option, Option))> { self.a.next().map(|(ak, av)| (ak, (Some(av), None))) } #[allow(clippy::type_complexity)] fn next_b(&mut self) -> Option<(K, (Option, Option))> { self.b.next().map(|(bk, bv)| (bk, (None, Some(bv)))) } } impl Iterator for OuterJoin where K: Ord, I: Iterator, J: Iterator, { type Item = (K, (Option, Option)); fn next(&mut self) -> Option { if let (Some((ak, _)), Some((bk, _))) = (self.a.peek(), self.b.peek()) { match ak.cmp(&bk) { Less => self.next_a(), Greater => self.next_b(), Equal => self .a .next() .and_then(|(ak, av)| self.b.next().map(|(_, bv)| (ak, (Some(av), Some(bv))))), } } else { self.next_a().or_else(|| self.next_b()) } } fn size_hint(&self) -> (usize, Option) { let (amin, amax) = self.a.size_hint(); let (bmin, bmax) = self.b.size_hint(); let rmin = max(amin, bmin); let rmax = amax.and_then(|amax| bmax.map(|bmax| amax + bmax)); (rmin, rmax) } } impl Clone for OuterJoin where I::Item: Clone, J::Item: Clone, { fn clone(&self) -> Self { Self { a: self.a.clone(), b: self.b.clone(), } } } #[derive(Clone, Debug)] pub struct Keys { pub(crate) i: I, } impl Iterator for Keys where K: Ord, I: Iterator, { type Item = K; fn next(&mut self) -> Option { self.i.next().map(|(k, _)| k) } fn size_hint(&self) -> (usize, Option) { self.i.size_hint() } } impl> ExactSizeIterator for Keys { fn len(&self) -> usize { self.i.len() } } impl> DoubleEndedIterator for Keys { fn next_back(&mut self) -> Option { self.i.next_back().map(|(k, _)| k) } } #[derive(Clone, Debug)] pub struct MapValues { pub(crate) i: I, pub(crate) f: F, } impl Iterator for MapValues where K: Ord, I: Iterator, F: FnMut(V) -> W, { type Item = (K, W); fn next(&mut self) -> Option { self.i.next().map(|(k, v)| (k, (self.f)(v))) } fn size_hint(&self) -> (usize, Option) { self.i.size_hint() } } impl ExactSizeIterator for MapValues where I: ExactSizeIterator + Iterator, F: FnMut(V) -> W, { fn len(&self) -> usize { self.i.len() } } impl DoubleEndedIterator for MapValues where I: DoubleEndedIterator + Iterator, F: FnMut(V) -> W, { fn next_back(&mut self) -> Option { self.i.next_back().map(|(k, v)| (k, (self.f)(v))) } } #[derive(Clone, Debug)] pub struct FilterMapValues { pub(crate) i: I, pub(crate) f: F, } impl Iterator for FilterMapValues where K: Ord, I: Iterator, F: FnMut(V) -> Option, { type Item = (K, W); fn next(&mut self) -> Option { while let Some((k, v)) = self.i.next() { if let Some(w) = (self.f)(v) { return Some((k, w)); } } None } fn size_hint(&self) -> (usize, Option) { let (_, imax) = self.i.size_hint(); (0, imax) } } #[derive(Clone, Debug)] pub struct AssumeSortedByKey { pub(crate) i: I, } impl Iterator for AssumeSortedByKey { 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 AssumeSortedByKey where I: ExactSizeIterator {} impl FusedIterator for AssumeSortedByKey where I: FusedIterator {} impl DoubleEndedIterator for AssumeSortedByKey where I: DoubleEndedIterator, { fn next_back(&mut self) -> Option { self.i.next_back() } } // not sure how to model this: an iterator that is sorted by key automatically sorted by item as well, // since the key comes first in the order of a pair. The reverse is not true, since e.g. (0,1), (0,2) // are sorted by item, but not strictly sorted by key! // mark common std traits impl SortedByKey for iter::Empty {} impl SortedByKey for iter::Once {} impl<'a, T> SortedByKey for option::Iter<'a, T> {} impl<'a, T> SortedByKey for result::Iter<'a, T> {} impl SortedByKey for option::IntoIter {} impl SortedByKey for result::IntoIter {} impl SortedByKey for iter::Enumerate {} impl SortedByKey for Pairs {} impl SortedByKey for MapValues {} impl SortedByKey for FilterMapValues {} impl SortedByKey for iter::Take {} impl SortedByKey for iter::Skip {} impl SortedByKey for iter::StepBy {} impl SortedByKey for iter::Cloned {} impl SortedByKey for iter::Copied {} impl SortedByKey for iter::Fuse {} impl SortedByKey for iter::Inspect {} impl SortedByKey for iter::TakeWhile {} impl SortedByKey for iter::SkipWhile {} impl SortedByKey for iter::Filter {} impl SortedByKey for iter::Peekable {} impl SortedByKey for iter::Zip {} impl SortedByKey for Join {} impl SortedByKey for LeftJoin {} impl SortedByKey for RightJoin {} impl SortedByKey for OuterJoin {} impl SortedByKey for AssumeSortedByKey {} impl SortedByKey for collections::btree_map::IntoIter {} impl<'a, K, V> SortedByKey for collections::btree_map::Iter<'a, K, V> {} impl<'a, K, V> SortedByKey for collections::btree_map::IterMut<'a, K, V> {} impl<'a, K, V> SortedByKey for collections::btree_map::Range<'a, K, V> {} impl<'a, K, V> SortedByKey for collections::btree_map::RangeMut<'a, K, V> {} impl SortedByKey for Box {} impl SortedByKey for iter::Map {} impl SortedByKey for iter::FlatMap where Iin: OneOrLess, J: IntoIterator, Iout: SortedByKey, { } impl SortedByKey for iter::Flatten where Iin: OneOrLess + Iterator, J: IntoIterator, Iout: SortedByKey, { } #[cfg(test)] mod tests { extern crate maplit; use super::*; use collections::BTreeMap; use core::fmt::Debug; use maplit::*; /// just a helper to get good output when a check fails fn unary_op(x: E, expected: R, actual: R) -> bool { let res = expected == actual; if !res { println!("x:{:?} expected:{:?} actual:{:?}", x, expected, actual); } res } /// 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 = BTreeMap; #[quickcheck] fn join(a: Reference, b: Reference) -> bool { type Result = BTreeMap; let expected: Result = a .keys() .intersection(b.keys()) .map(|k| (k.clone(), (a[k], b[k]))) .collect(); let actual: Result = a.clone().into_iter().join(b.clone().into_iter()).collect(); binary_op(a, b, expected, actual) } #[quickcheck] fn left_join(a: Reference, b: Reference) -> bool { type Result = BTreeMap)>; let expected: Result = a .keys() .map(|k| (k.clone(), (a[k], b.get(k).cloned()))) .collect(); let actual: Result = a .clone() .into_iter() .left_join(b.clone().into_iter()) .collect(); binary_op(a, b, expected, actual) } #[quickcheck] fn right_join(a: Reference, b: Reference) -> bool { type Result = BTreeMap, Element)>; let expected: Result = b .keys() .map(|k| (k.clone(), (a.get(k).cloned(), b[k]))) .collect(); let actual: Result = a .clone() .into_iter() .right_join(b.clone().into_iter()) .collect(); binary_op(a, b, expected, actual) } #[quickcheck] fn outer_join(a: Reference, b: Reference) -> bool { type Result = BTreeMap, Option)>; let expected: Result = a .keys() .union(b.keys()) .map(|k| (k.clone(), (a.get(k).cloned(), b.get(k).cloned()))) .collect(); let actual: Result = a .clone() .into_iter() .outer_join(b.clone().into_iter()) .collect(); binary_op(a, b, expected, actual) } #[quickcheck] fn map_values(x: Reference) -> bool { type Result = BTreeMap; let expected: Result = x.clone().into_iter().map(|(k, v)| (k, v * 2)).collect(); let actual: Result = x.clone().into_iter().map_values(|v| v * 2).collect(); unary_op(x, expected, actual) } #[quickcheck] fn filter_map_values(x: Reference) -> bool { type Result = BTreeMap; let expected: Result = x .clone() .into_iter() .filter_map(|(k, v)| if v % 2 != 0 { Some((k, v * 2)) } else { None }) .collect(); let actual: Result = x .clone() .into_iter() .filter_map_values(|v| if v % 2 != 0 { Some(v * 2) } else { None }) .collect(); unary_op(x, expected, actual) } fn is_s + SortedByKey>(_v: I) {} fn s() -> impl Iterator + SortedByKey { (0i64..10).pairs() } #[test] fn instances() { // creation is_s(iter::empty::<(i64, ())>()); is_s(iter::once((0, ()))); is_s([1, 2, 3, 4].iter().enumerate()); // ranges is_s((0i64..10).pairs()); is_s((0i64..=10).pairs()); is_s((0i64..).pairs()); // wrappers is_s(Box::new((0i64..).pairs())); // skip/take/step/filter is_s(s().step_by(1)); is_s(s().take(1)); is_s(s().skip(1)); is_s(s().take_while(|_| true)); is_s(s().skip_while(|_| true)); is_s(s().filter(|_| true)); // identity is_s(s().peekable()); is_s(s().fuse()); is_s(s().inspect(|_| {})); // relational is_s(s().join(s())); is_s(s().left_join(s())); is_s(s().right_join(s())); is_s(s().outer_join(s())); // btreeset is_s(btreemap! { 0i64 => "" }.iter()); is_s(btreemap! { 0i64 => "" }.into_iter()); is_s(btreemap! { 0i64 => "" }.iter_mut()); is_s(btreemap! { 0i64 => "" }.range(..)); is_s(btreemap! { 0i64 => "" }.range_mut(..)); // one_or_less let a_btree = BTreeMap::::new(); is_s( Some(()) .iter() .map(|_| &a_btree) .filter(|b| !b.is_empty()) .flatten(), ); is_s( iter::once(Result::::Ok(12)) .flatten() .map(|_| &a_btree) .filter(|b| !b.is_empty()) .flat_map(|m| m.iter()), ); } }