1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
//! This tiny crate should help you simplify your code when you need to wrap
//! [`Iterator`] as trait-object.
//!
//! [`iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html
//!
//! 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.
//!
//! ```
//! # #[derive(Debug, Clone, Copy, PartialEq, Eq)]
//! # enum Color { Red, Green, Blue, White, Black }
//! struct Flag {
//!     primary_colors: std::collections::HashSet<Color>,
//!     secondary_colors: std::collections::HashSet<Color>,
//! }
//! ```
//!
//! you might implement a `fn colors()` that look like this
//!
//! ```
//! # use dyn_iter::DynIter;
//! # #[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;
//! # }
//! # struct Flag {
//! #     primary_colors: std::collections::HashSet<Color>,
//! #     secondary_colors: std::collections::HashSet<Color>,
//! # }
//! # impl<'a> Colors<'a> for Flag {
//! #   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()
//! #   )
//! }
//! # }
//! ```
//!
//! 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.
//!
//! ```
//! # use dyn_iter::DynIter;
//! # #[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;
//! # }
//! # struct Flag {
//! #     primary_colors: std::collections::HashSet<Color>,
//! #     secondary_colors: std::collections::HashSet<Color>,
//! # }
//! impl<'a> Colors<'a> for Flag {
//!     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].
//!
//! [blog post]: https://hole.tuziwo.info/dyn-iterator.html
#![warn(
    missing_docs,
    missing_doc_code_examples,
    missing_copy_implementations,
    missing_debug_implementations,
    missing_docs,
    rust_2018_idioms
)]
use std::fmt::{Debug, Formatter};

/// Iterator type that can wrap any kind of [`Iterator`].
///
/// This `struct` is a wrapper around types that implements `Iterator`
/// trait. Since we do not know which specific type of `Iterator` is
/// used, we `Box` it as a trait-object.
///
/// This iterator yields any type which usually depends on references on the
/// model.  Therefore, the iterator must outlive the wrapped `Iterator`.
///
/// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html
pub struct DynIter<'iter, V> {
    iter: Box<dyn Iterator<Item = V> + 'iter>,
}

impl<V> Debug for DynIter<'_, V> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let size_str = match self.iter.size_hint() {
            (min, None) => format!("{}", min),
            (min, Some(max)) if min == max => format!("{}", min),
            (min, Some(max)) => format!("between {} and {}", min, max),
        };
        write!(f, "{{ iter: [Iterator with {} elements]}}", size_str,)
    }
}

impl<'iter, V> DynIter<'iter, V> {
    /// Instantiates an [`DynIter`] from any kind of [`Iterator`].
    ///
    /// [`DynIter`]: ./struct.DynIter.html
    /// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html
    pub fn new<I>(iter: I) -> Self
    where
        I: Iterator<Item = V> + 'iter,
    {
        Self {
            iter: Box::new(iter),
        }
    }
}

impl<'iter, V> Iterator for DynIter<'iter, V> {
    type Item = V;
    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next()
    }
}

#[cfg(test)]
mod tests {
    use super::DynIter;

    // This test is mostly checking that everything compiles and works as
    // expected.
    #[test]
    fn it_compiles() {
        let iter = (0..5).skip(2).filter(|n| *n != 3);
        let mut dyn_iter = DynIter::new(iter);
        assert_eq!(dyn_iter.next(), Some(2));
        assert_eq!(dyn_iter.next(), Some(4));
        assert_eq!(dyn_iter.next(), None);
    }

    struct SizeHintIterator {
        min: usize,
        max: Option<usize>,
    }

    mod debug {
        use super::*;

        impl Iterator for SizeHintIterator {
            type Item = u8;
            fn next(&mut self) -> Option<Self::Item> {
                Some(1)
            }
            fn size_hint(&self) -> (usize, Option<usize>) {
                (self.min, self.max)
            }
        }

        #[test]
        fn no_max_size_hint() {
            let iter = SizeHintIterator { min: 2, max: None };
            let dyn_iter = DynIter::new(iter);
            let debug_msg = format!("{:?}", dyn_iter);
            assert_eq!("{ iter: [Iterator with 2 elements]}", debug_msg);
        }

        #[test]
        fn equal_min_max_size_hint() {
            let iter = SizeHintIterator {
                min: 3,
                max: Some(3),
            };
            let dyn_iter = DynIter::new(iter);
            let debug_msg = format!("{:?}", dyn_iter);
            assert_eq!("{ iter: [Iterator with 3 elements]}", debug_msg);
        }

        #[test]
        fn different_min_max_size_hint() {
            let iter = SizeHintIterator {
                min: 4,
                max: Some(5),
            };
            let dyn_iter = DynIter::new(iter);
            let debug_msg = format!("{:?}", dyn_iter);
            assert_eq!(
                "{ iter: [Iterator with between 4 and 5 elements]}",
                debug_msg
            );
        }
    }
}