#iterator #dynamic

dyn-iter

Wrapper around Box<dyn Iterator<Item = V> + 'iter> to simplify your code

2 unstable releases

0.2.0 Sep 28, 2020
0.1.0 Sep 22, 2020

#1246 in Rust patterns

Download history 36/week @ 2022-12-04 90/week @ 2022-12-11 42/week @ 2022-12-18 5/week @ 2022-12-25 24/week @ 2023-01-01 105/week @ 2023-01-08 82/week @ 2023-01-15 27/week @ 2023-01-22 115/week @ 2023-01-29 69/week @ 2023-02-05 80/week @ 2023-02-12 90/week @ 2023-02-19 159/week @ 2023-02-26 109/week @ 2023-03-05 79/week @ 2023-03-12

441 downloads per month

MIT license

16KB
96 lines

dyn-iter

continuous-integration-badge code-coverage-badge crates.io-badge license-badge documentation-badge

This tiny crate should help you simplify your code when you need to wrap Iterator as trait-object.

Imagine for example a trait like the following.

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Color {
    Red,
    Green,
    Blue,
    White,
    Black,
}
trait Colors<'a> {
    type ColorsIter: Iterator<Item = Color>;
    fn colors(&'a self) -> Self::ColorsIter;
}

As an implementor, you have a struct Flag that looks like this.

struct Flag {
    primary_colors: HashSet<Color>,
    secondary_colors: HashSet<Color>,
}

you might implement a fn colors() that look like this

fn colors(&'a self) -> Self::ColorsIter {
    self.primary_colors
        .iter()
        .chain(&self.secondary_colors)
        .filter(|color| **color != Color::Black)
        .copied()
}

With the above implementation, defining the associated type ColorsIter might be difficult. DynIter should simplify your life because you can just write the following implementation.

trait Colors<'a> {
    type ColorsIter = DynIter<'a, Color>;
    fn colors(&'a self) -> Self::ColorsIter {
        DynIter::new(
            self.primary_colors
                .iter()
                .chain(&self.secondary_colors)
                .filter(|color| **color != Color::Black)
                .copied()
        )
    }
}

Behind the scene, DynIter<'iter, V> is only providing a wrapper around a Box<dyn Iterator<Item = V> + 'iter>.

For more details about why this crate exists, read this blog post.

No runtime deps