#iterator #chain #fallback #data-structures #no-alloc

no-std empty-fallback-chain

Iterator adaptor like chain, but conditional on empty first iterator

2 stable releases

1.0.1 Jul 2, 2024
1.0.0 Jul 1, 2024

#1067 in Algorithms

MPL-2.0 license

31KB
342 lines

empty-fallback-chain

Simple rust library that provides an iterator-combinator - similar to core::iter::Chain - that takes two iterators and glues them together, one after the other. However, unlike that combinator, this one will only run through the second iterator if the first iterator never produces any value. To get started, see IteratorExt::empty_fallback_chain

This is highly useful when you have a collection of iterators and want to take values from the first one that produces something. The combinator in this library is guaranteed not to attempt to read any values from the second iterator unless the first iterator produces nothing, so it is very good at being lazy.

The code in this library also takes a lot of implementation infrastructure from inside the Standard Library's implementation of Chain. This is important, because - especially with nested chaining - it would be very easy to accidentally create very challenging-to-optimise call chains. By using the work the Rust Standard Library Maintainers have already done to make their own implementation "optimiser friendly", we can hopefully avoid many performance pitfalls.

In future, it might be possible to implement more powerful features, like the ability to do some kind of interesting threshold chaining where you can pick the first "k" of "n" iterators. The main way I can see to do this is to make some sort of macro that creates a structure with a threshold counter. But that's not the focus right now, and this library will likely reach some sort of "complete" status in very near future unless there is a pressing need for this functionality.

No runtime deps