Is there a filter iterator that can also peek one item ahead? For example, if I have a function that says whether a byte should be skipped (based on both the byte itself and the next byte):
// Returns true if `byte` should be skipped.
// Or false otherwise.
fn skip_byte(byte: u8, next: Option<u8>) -> bool {
match next {
Some(n) => byte == n,
_ => false
}
}
Then can I use it to filter a list, like this:
fn main() {
let bytes = [0u8, 1,2, 3, 3, 4, 4, 5];
// Uses a hypothetical `peek_filter` iterator.
let result = bytes.iter().peek_filter(skip_byte).collect();
}
But you can't use peek inside the filter function.
let a = [5u8,7,9,42,1,8];
let mut peekable = a.iter().peekable();
let mut iter = peekable.filter(|x| {
match peekable.peek() {
Some(n) => **n == **x,
None => false
}
});
iter.next();
According to SO, it wasn't possible in 2017 and I have a feeling it's still not possible. The above code works and I guess you could somehow hack on an addition to the Peekable or Iterator to create a callable fn (maybe?)