Harry
Harry

Reputation: 3052

How to peek to the previous element of a Peekable struct

I'm trying to find the first pair of indices of two lists where the mismatch happens. But with my current implementation using Peekable struct, the tuple result returned by mismatch function is 1 element ahead because of which the assertion is getting failed. Is it possible to peek to the previous element?

use std::iter::Peekable;

pub fn mismatch<'a, 'b, FirstList, FirstItemType, SecondList, SecondItemType, BinaryPredicate>(
    first_list: FirstList,
    second_list: SecondList,
    binary_predicate: BinaryPredicate) -> (Peekable<<FirstList as IntoIterator>::IntoIter>, Peekable<<SecondList as IntoIterator>::IntoIter>)
where
    FirstList: IntoIterator<Item = &'a FirstItemType>,
    FirstItemType: 'a,
    SecondList: IntoIterator<Item = &'b SecondItemType>,
    SecondItemType: 'b,
    BinaryPredicate: Fn(&FirstItemType, &SecondItemType) -> bool
{
    let mut f_itr = first_list.into_iter().peekable();
    let mut s_itr = second_list.into_iter().peekable();

    while f_itr.peek().is_some() && s_itr.peek().is_some() {
        let res = binary_predicate(f_itr.next().as_ref().unwrap(), s_itr.next().as_ref().unwrap());
        if !res {
            return (f_itr, s_itr);
        }
    }

    (f_itr, s_itr)
}

fn main() {
    let first_list = vec![1, 2, 3, 4, 5, 6];
    let second_list = vec![1, 2, 3, 5, 6, 7];

    let mut res = mismatch(&first_list, &second_list, |first_item, second_item| {
        *first_item == *second_item
    });

    assert_eq!(res.0.peek(), Some(&first_list[3]).as_ref()); // fails as it 1 element ahead of the first mismatch
    assert_eq!(res.1.peek(), Some(&second_list[3]).as_ref()); // fails as it 1 element ahead of the first mismatch
}

Assertion Failure

thread 'main' panicked at src/main.rs:35:5:
assertion `left == right` failed
  left: Some(5)
 right: Some(4)
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Upvotes: 0

Views: 34

Answers (0)

Related Questions