#iterator #zip #product #data-structures

no-std lockstep

An iterator adaptor for selective zipping

4 releases (2 breaking)

0.3.0 Feb 7, 2025
0.2.0 Jan 29, 2025
0.1.1 Jan 28, 2025
0.1.0 Jan 28, 2025

#1228 in Algorithms

Download history 284/week @ 2025-01-26 150/week @ 2025-02-02 31/week @ 2025-02-09 3/week @ 2025-02-16

468 downloads per month

MIT/Apache

10KB
136 lines

A lockstep iterator adaptor

The lockstep iterator adaptor is an adapter similar to zip, but instead uses a control flow closure to selectively skip elements from either the left or the right iterator, or yield the pair. This adaptor is primarily useful when working with sorted data.

The main entrypoint is the lockstep function.

This crate is #![no_std] and #![forbid(unsafe_code)].

Examples

Re-implement zip.

use lockstep::{lockstep, Control};

pub fn zip<L, R>(left: L, right: R) -> impl Iterator<Item = (L::Item, R::Item)>
where
    L: IntoIterator,
    R: IntoIterator,
{
    lockstep(left.into_iter(), right.into_iter(), |_, _| Control::Yield)
}

Compose two sorted iterators to only yield elements which they have in common.

use core::cmp::Ordering;

use lockstep::{lockstep, Control};

/// Assumes that `left` and `right` are sorted.
pub fn intersection<L, R, T>(left: L, right: R) -> impl Iterator<Item = T>
where
    L: IntoIterator<Item = T>,
    R: IntoIterator<Item = T>,
    T: Ord,
{
    lockstep(left.into_iter(), right.into_iter(), |l, r| {
        match l.cmp(r) {
            Ordering::Less => Control::SkipLeft,
            Ordering::Equal => Control::Yield,
            Ordering::Greater => Control::SkipRight,
        }
    })
    .map(|(l, _)| l)
}

No runtime deps