iter-merge
A high-performance iterator merging library for Rust that efficiently combines multiple iterators into a single iterator, yielding smallest item first.
Note: only compares the first items across provided iterators. The output would be sorted only if the iterators themselves are sorted.
Features
- Optimized for small to medium numbers of iterators
- Lazy iterator consumption: each
.next()
advances only one iterator - Support for custom comparison functions
- Multiple storage backends:
Vec
andStackVec
(for no-std and no-alloc compatibility) - Optionally
forbid_unsafe
- Dynamic iterator addition after construction
- Additional
Peekable
methods
Usage
use Merged;
let iter1 = vec!;
let iter2 = vec!;
let mut merged = new.build;
let result = merged.into_vec;
assert_eq!;
Custom Comparison
use Merged;
let mut merged = new
.with_cmp
.build;
let result = merged.into_vec;
assert_eq!;
Dynamic Iterator Addition
use Merged;
let mut merged = new.build;
assert_eq!;
merged.add_iter;
merged.add_iters;
let result = merged.into_vec;
assert_eq!;
Performance
This library is optimized for merging small to medium numbers of iterators. When tested
with ~1 000 000 random u64
s:
- Up to ~123 iterators: 2x faster than
itertools::kmerge
- Up to ~355 iterators: 1.5x faster than
itertools::kmerge
- Break-even point: ~682 iterators, after that the
O(iterator_count²)
starts to dominate - Performs better when an iterator contains a run of the min items
- Arbitrary tie-breaking: 23% faster than stable tie-breaking
- Unsafe optimizations: 49% faster than safe-only mode
Features
The crate supports several feature flags:
vec_storage
(default): Enable heap-allocated storage withVec
, requiresalloc
stackvec_storage
: Enable stack-allocated storage withStackVec
forbid_unsafe
: Disable all unsafe code
Testing
Run the fuzz test:
- Uncomment
For fuzzing
blocks in the Cargo.toml or run./toggle_fuzz_config.sh
- Run tests:
Run benchmarks:
RUSTFLAGS='-C target-cpu=native --cfg benchmarking'
(Benchmarking dependencies are behind benchmarking
cfg option to keep MSRV low)
MSRV
The minimum supported Rust version for this crate is 1.68.0. This may change in a major release, but it is unlikely.
Contributing
Contributions are welcome. For major changes, please open an issue first to discuss what you would like to change.
Related Projects
itertools
- General iterator utilities (includeskmerge
)