1 unstable release

0.1.0 May 12, 2021

#1789 in Rust patterns

MIT/Apache

15KB
319 lines

Tee for iterators

crates.io docs.rs License Dependencies

License

Licensed under either of

at your option.


lib.rs:

Make several clones of an iterator.

Each handle to the iterator is represented with an instance of [Tee]. A Tee is itself an iterator which will yield the same sequence of items as the original iterator. A Tee can be freely cloned at any point to create more handles to the same underlying iterator. Once cloned, the two Tees are identical, but separate: they will yield the same items.

The implementation uses a single ring buffer for storing items already pulled from the underlying iterator, but not yet consumed by all the Tees. The buffer is protected with a RwLock, and atomics are used to keep item reference counts.

While the implementation tries to be efficient, it will not be as efficient as natively cloning the underlying iterator if it implements Clone.

Examples

use iter_tee::Tee;

// Wrap an iterator in a Tee:
let mut tee1 = Tee::new(0..10);
// It yields the same items:
assert_eq!(tee1.next(), Some(0));
assert_eq!(tee1.next(), Some(1));
// Create a second Tee:
let mut tee2 = tee1.clone();
// Both yield the same items:
assert_eq!(tee1.next(), Some(2));
assert_eq!(tee2.next(), Some(2));
// Create a third Tee:
let mut tee3 = tee2.clone();
// All three yield the same items:
assert_eq!(tee1.next(), Some(3));
assert_eq!(tee2.next(), Some(3));
assert_eq!(tee3.next(), Some(3));
// The Tees can be advanced independently:
assert_eq!(tee1.next(), Some(4));
assert_eq!(tee1.next(), Some(5));
assert_eq!(tee2.next(), Some(4));

No runtime deps