orx_concurrent_iter/pullers/
enumerated_item_puller.rs

1use crate::concurrent_iter::ConcurrentIter;
2
3/// A regular [`Iterator`] which is created from and linked to and
4/// pulls its elements from a [`ConcurrentIter`].
5///
6/// It can be created using the [`item_puller_with_idx`] method of a concurrent iterator.
7///
8/// This is similar to [`ItemPuller`] except that this iterator additionally returns the
9/// indices of the elements in the source concurrent iterator.
10///
11/// [`item_puller_with_idx`]: crate::ConcurrentIter::item_puller_with_idx
12/// [`ItemPuller`]: crate::ItemPuller
13///
14/// # Examples
15///
16/// See the [`ItemPuller`] for detailed examples.
17/// The following example only demonstrates the additional index that is returned by the
18/// next method of the `EnumeratedItemPuller`.
19///
20/// ```
21/// use orx_concurrent_iter::*;
22///
23/// let num_threads = 4;
24/// let data: Vec<_> = (0..100).map(|x| x.to_string()).collect();
25/// let con_iter = data.con_iter();
26///
27/// std::thread::scope(|s| {
28///     for _ in 0..num_threads {
29///         s.spawn(|| {
30///             for (idx, value) in con_iter.item_puller_with_idx() {
31///                 assert_eq!(value, &idx.to_string());
32///             }
33///         });
34///     }
35/// });
36/// ```
37pub struct EnumeratedItemPuller<'a, I>
38where
39    I: ConcurrentIter,
40{
41    con_iter: &'a I,
42}
43
44impl<'i, I> From<&'i I> for EnumeratedItemPuller<'i, I>
45where
46    I: ConcurrentIter,
47{
48    fn from(con_iter: &'i I) -> Self {
49        Self { con_iter }
50    }
51}
52
53impl<I> Iterator for EnumeratedItemPuller<'_, I>
54where
55    I: ConcurrentIter,
56{
57    type Item = (usize, I::Item);
58
59    #[inline(always)]
60    fn next(&mut self) -> Option<Self::Item> {
61        self.con_iter.next_with_idx()
62    }
63}