Crates.io | peek-again |
lib.rs | peek-again |
version | 0.1.1 |
source | src |
created_at | 2024-11-09 02:27:55.802859 |
updated_at | 2024-11-09 20:59:53.771626 |
description | A performant iterator providing double peek functionality. |
homepage | https://github.com/CleveGreen/peek-again |
repository | https://github.com/CleveGreen/peek-again |
max_upload_size | |
id | 1441774 |
size | 66,959 |
A performant iterator providing double peek functionality.
This crate provides a Peekable
iterator adapter that allows looking ahead by up to two elements without advancing the
iterator. It maintains performance parity with core::iter::Peekable
for single peek operations, with only a minimal 90 picosecond overhead for double peek operations.
core::iter::Peekable
.use peek_again::Peekable;
let mut iter = Peekable::new([1, 2, 3].into_iter());
assert_eq!(iter.peek().get(), Some(&1)); // Look at next element
assert_eq!(iter.peek_2(), Some(&2)); // Look two elements ahead
assert_eq!(iter.next(), Some(1)); // Iterator position unchanged
The Peek
type returned by
peek
provides
additional control over iteration:
# use peek_again::Peekable;
let mut iter = Peekable::new([1, 2, 3].into_iter());
let mut peek = iter.peek();
// Examine current and next elements
assert_eq!(peek, Some(&1));
assert_eq!(peek.peek(), Some(&2));
// Conditionally consume elements (moving the iterator forward)
if peek == Some(&1) {
assert_eq!(peek.consume(), Some(1));
}
The drain_if
method
allows consuming multiple elements based on lookahead:
# use peek_again::Peekable;
let mut iter = Peekable::new([1, 2, 3].into_iter());
let peek = iter.peek();
peek.drain_if(|&next| next == 2)
.map_or_else(
|_peek| unreachable!("The second element is two."),
|(curr, next)| {
assert_eq!(curr, Some(1));
assert_eq!(next, 2);
}
);
peek()
) are optimized to match or exceed the performance of
core::iter::Peekable
.peek_2()
) incur only a 90 picosecond overhead compared to
single peek operations.This crate is marked with #![forbid(unsafe_code)]
and employs design by contract
principles, making the property tests far more meaningful.