1 use crate::iter::plumbing::*;
2 use crate::iter::*;
3
4 /// Creates a parallel iterator that produces an element exactly once.
5 ///
6 /// This admits no parallelism on its own, but it could be chained to existing
7 /// parallel iterators to extend their contents, or otherwise used for any code
8 /// that deals with generic parallel iterators.
9 ///
10 /// # Examples
11 ///
12 /// ```
13 /// use rayon::prelude::*;
14 /// use rayon::iter::once;
15 ///
16 /// let pi = (0..1234).into_par_iter()
17 /// .chain(once(-1))
18 /// .chain(1234..10_000);
19 ///
20 /// assert_eq!(pi.clone().count(), 10_001);
21 /// assert_eq!(pi.clone().filter(|&x| x < 0).count(), 1);
22 /// assert_eq!(pi.position_any(|x| x < 0), Some(1234));
23 /// ```
once<T: Send>(item: T) -> Once<T>24 pub fn once<T: Send>(item: T) -> Once<T> {
25 Once { item }
26 }
27
28 /// Iterator adaptor for [the `once()` function](fn.once.html).
29 #[derive(Clone, Debug)]
30 pub struct Once<T: Send> {
31 item: T,
32 }
33
34 impl<T: Send> ParallelIterator for Once<T> {
35 type Item = T;
36
drive_unindexed<C>(self, consumer: C) -> C::Result where C: UnindexedConsumer<Self::Item>,37 fn drive_unindexed<C>(self, consumer: C) -> C::Result
38 where
39 C: UnindexedConsumer<Self::Item>,
40 {
41 self.drive(consumer)
42 }
43
opt_len(&self) -> Option<usize>44 fn opt_len(&self) -> Option<usize> {
45 Some(1)
46 }
47 }
48
49 impl<T: Send> IndexedParallelIterator for Once<T> {
drive<C>(self, consumer: C) -> C::Result where C: Consumer<Self::Item>,50 fn drive<C>(self, consumer: C) -> C::Result
51 where
52 C: Consumer<Self::Item>,
53 {
54 consumer.into_folder().consume(self.item).complete()
55 }
56
len(&self) -> usize57 fn len(&self) -> usize {
58 1
59 }
60
with_producer<CB>(self, callback: CB) -> CB::Output where CB: ProducerCallback<Self::Item>,61 fn with_producer<CB>(self, callback: CB) -> CB::Output
62 where
63 CB: ProducerCallback<Self::Item>,
64 {
65 // Let `OptionProducer` handle it.
66 Some(self.item).into_par_iter().with_producer(callback)
67 }
68 }
69