stacks_common/util/pair.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// Borrowed from Andrew Poelstra's rust-bitcoin library
/// An iterator that returns pairs of elements
pub struct Pair<I>
where
I: Iterator,
{
iter: I,
last_elem: Option<I::Item>,
}
impl<I: Iterator> Iterator for Pair<I> {
type Item = (I::Item, I::Item);
#[inline]
fn next(&mut self) -> Option<(I::Item, I::Item)> {
let elem1 = self.iter.next();
if let Some(elem1) = elem1 {
if let Some(elem2) = self.iter.next() {
Some((elem1, elem2))
} else {
self.last_elem = Some(elem1);
None
}
} else {
None
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
match self.iter.size_hint() {
(n, None) => (n / 2, None),
(n, Some(m)) => (n / 2, Some(m / 2)),
}
}
}
impl<I: Iterator> Pair<I> {
/// Returns the last element of the iterator if there were an odd
/// number of elements remaining before it was Pair-ified.
#[inline]
pub fn remainder(self) -> Option<I::Item> {
self.last_elem
}
}
/// Returns an iterator that returns elements of the original iterator 2 at a time
pub trait Pairable: Sized + Iterator {
/// Returns an iterator that returns elements of the original iterator 2 at a time
fn pair(self) -> Pair<Self>;
}
impl<I: Iterator> Pairable for I {
/// Creates an iterator that yields pairs of elements from the underlying
/// iterator, yielding `None` when there are fewer than two elements to
/// return.
#[inline]
fn pair(self) -> Pair<I> {
Pair {
iter: self,
last_elem: None,
}
}
}