Crate peekmore

source ·
Expand description

Synopsis:

This crate introduces a multi-peekable iterator. The iterator is similar to Peekable. The main difference is that Peekable only allows you to peek at the next element and no further. When using PeekMore however, you can peek at as many elements as you want.

A peek at how it works:

To enable peeking at multiple elements ahead of consuming a next element, the iterator uses a traversable queue which holds the elements which you can peek at, but have not been consumed (yet). The underlying data structure of this queue can be a Vec, or a SmallVec from the smallvec crate. By default, the SmallVec is used. SmallVec uses the stack for a limited amount of elements and will only allocate on the heap if this maximum amount of elements is reached.

Illustrated example:

An illustrated example can be found at the PeekMoreIterator::peek documentation.

Usage example:

use peekmore::PeekMore;

let iterable = [1, 2, 3, 4];
let mut iter = iterable.iter().peekmore();

// Peek at the first element.
let v1 = iter.peek();
assert_eq!(v1, Some(&&1));

// Consume the first element.
let v1c = iter.next();
assert_eq!(v1c, Some(&1));

// Peek at the second element (the element our cursor points at also moved to the second element,
// since the first element was consumed.)
let v2 = iter.peek();
assert_eq!(v2, Some(&&2));

// Advance the cursor. The cursor will now point to the third element.
let _ = iter.advance_cursor();

// Check that it is indeed at the third element.
let v3 = iter.peek();
assert_eq!(v3, Some(&&3));

// Reset the position the cursor points at. The cursor will point to the first unconsumed element
// again.
iter.reset_cursor();

// Check that we are indeed at the second element again.
let v2 = iter.peek();
assert_eq!(v2, Some(&&2));

// Shift the position of the cursor to the right twice by chaining the advance_view method.
let _ = iter.advance_cursor().advance_cursor();

// Verify that the cursor indeed points at the fourth element.
let v4 = iter.peek();
assert_eq!(v4, Some(&&4));

// Reset the position which the cursor points at again.
iter.reset_cursor();

// We can also advance the cursor and peek with a single operation.
let v3 = iter.peek_next();
assert_eq!(v3, Some(&&3));

Structs

  • This iterator makes it possible to peek multiple times without consuming a value. In reality the underlying iterator will be consumed, but the values will be stored in a queue. This queue allows us to peek at unconsumed elements (as far as the multi-peek iterator is concerned). When the iterator consumes an element, the element at the front of the queue will be dequeued, and will no longer be peekable.

Enums

Traits

  • Trait which allows you to create the multi-peek iterator. It allows you to peek at any unconsumed element. Elements can be consumed using the next method defined on any Iterator.