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
use iter::*;
use iter::internal::*;
use std;
use std::sync::atomic::{AtomicBool, Ordering};
impl<T: Send> IntoParallelIterator for Option<T> {
type Item = T;
type Iter = IntoIter<T>;
fn into_par_iter(self) -> Self::Iter {
IntoIter { opt: self }
}
}
impl<'a, T: Sync> IntoParallelIterator for &'a Option<T> {
type Item = &'a T;
type Iter = Iter<'a, T>;
fn into_par_iter(self) -> Self::Iter {
Iter { inner: self.as_ref().into_par_iter() }
}
}
impl<'a, T: Send> IntoParallelIterator for &'a mut Option<T> {
type Item = &'a mut T;
type Iter = IterMut<'a, T>;
fn into_par_iter(self) -> Self::Iter {
IterMut { inner: self.as_mut().into_par_iter() }
}
}
pub struct IntoIter<T: Send> {
opt: Option<T>,
}
impl<T: Send> ParallelIterator for IntoIter<T> {
type Item = T;
fn drive_unindexed<C>(self, consumer: C) -> C::Result
where C: UnindexedConsumer<Self::Item>
{
bridge(self, consumer)
}
fn opt_len(&mut self) -> Option<usize> {
Some(self.len())
}
}
impl<T: Send> IndexedParallelIterator for IntoIter<T> {
fn drive<C>(self, consumer: C) -> C::Result
where C: Consumer<Self::Item>
{
bridge(self, consumer)
}
fn len(&mut self) -> usize {
match self.opt {
Some(_) => 1,
None => 0,
}
}
fn with_producer<CB>(self, callback: CB) -> CB::Output
where CB: ProducerCallback<Self::Item>
{
callback.callback(OptionProducer { opt: self.opt })
}
}
delegate_indexed_iterator!{
#[doc = "Parallel iterator over an immutable reference to an option"]
Iter<'a, T> => IntoIter<&'a T>,
impl<'a, T: Sync + 'a>
}
delegate_indexed_iterator!{
#[doc = "Parallel iterator over a mutable reference to an option"]
IterMut<'a, T> => IntoIter<&'a mut T>,
impl<'a, T: Send + 'a>
}
struct OptionProducer<T: Send> {
opt: Option<T>,
}
impl<T: Send> Producer for OptionProducer<T> {
type Item = T;
type IntoIter = std::option::IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
self.opt.into_iter()
}
fn split_at(self, index: usize) -> (Self, Self) {
let none = OptionProducer { opt: None };
if index == 0 {
(none, self)
} else {
(self, none)
}
}
}
impl<'a, C, T> FromParallelIterator<Option<T>> for Option<C>
where C: FromParallelIterator<T>,
T: Send
{
fn from_par_iter<I>(par_iter: I) -> Self
where I: IntoParallelIterator<Item = Option<T>>
{
let found_none = AtomicBool::new(false);
let collection = par_iter
.into_par_iter()
.inspect(|item| if item.is_none() {
found_none.store(true, Ordering::Relaxed);
})
.while_some()
.collect();
if found_none.load(Ordering::Relaxed) {
None
} else {
Some(collection)
}
}
}