Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a PeekMap iterator adaptor #668

Open
tgross35 opened this issue Dec 29, 2022 · 1 comment
Open

Add a PeekMap iterator adaptor #668

tgross35 opened this issue Dec 29, 2022 · 1 comment

Comments

@tgross35
Copy link

tgross35 commented Dec 29, 2022

Add an iterator that allows mapping with (next_item, Option(&peek_item). This is useful for parsers. Exact semantics may vary, but the goal is to get something like tuple_windows without needing to clone

100% credit to @talchas on Discord (I don't see that user here) for the implementation:

use std::iter::Peekable;
pub struct PeekMap<I: Iterator, F>(Peekable<I>, F);
pub fn peek_map<R, I: Iterator, F: FnMut(I::Item, Option<&I::Item>) -> R>(it: Peekable<I>, f: F) -> PeekMap<I, F> {
    PeekMap(it, f)
}
impl<R, I: Iterator, F: FnMut(I::Item, Option<&I::Item>) -> R> Iterator for PeekMap<I, F> {
    type Item = R;
    fn next(&mut self) -> Option<R> {
        let x = self.0.next()?;
        Some((self.1)(x, self.0.peek()))
    }
}
@G-M0N3Y-2503
Copy link

Previously it looks like there was the desire to place this in std
#809
rust-lang/rust#118474

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants