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
use std::sync::Arc;

use crossbeam_channel::RecvError;

use crate::channel::ResultChannel;
use crate::worker::ThreadWorker;

pub struct ResultIter<'a, T>
where
    T: Send + 'static,
{
    result_channel: &'a Arc<ResultChannel<T>>,
}

impl<'a, T> ResultIter<'a, T>
where
    T: Send + 'static,
{
    pub fn new(result_channel: &'a Arc<ResultChannel<T>>) -> Self {
        Self { result_channel }
    }

    pub fn has_results(&self) -> bool {
        !self.result_channel.is_finished()
    }
}

impl<'a, T> Iterator for ResultIter<'a, T>
where
    T: Send + 'static,
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.has_results() {
            let result: Result<T, RecvError> = self.result_channel.recv();
            self.result_channel.status().set_concluded(true);
            if let Ok(result) = result {
                return Some(result);
            }
        }
        None
    }
}

pub struct YieldResultIter<'a, F, T>
where
    F: Fn() -> T + Send + 'static,
    T: Send + 'static,
{
    workers: &'a Vec<ThreadWorker<F, T>>,
    result_channel: &'a Arc<ResultChannel<T>>,
}

impl<'a, F, T> YieldResultIter<'a, F, T>
where
    F: Fn() -> T + Send + 'static,
    T: Send + 'static,
{
    pub fn new(
        workers: &'a Vec<ThreadWorker<F, T>>,
        result_channel: &'a Arc<ResultChannel<T>>,
    ) -> Self {
        Self {
            workers,
            result_channel,
        }
    }

    pub fn has_jobs(&self) -> bool {
        for worker in self.workers.iter() {
            if !worker.job_channel().is_finished() {
                return true;
            }
        }
        false
    }

    pub fn has_results(&self) -> bool {
        !self.result_channel.is_finished()
    }
}

impl<'a, F, T> Iterator for YieldResultIter<'a, F, T>
where
    F: Fn() -> T + Send + 'static,
    T: Send + 'static,
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.has_jobs() || self.has_results() {
            let result: Result<T, RecvError> = self.result_channel.recv();
            self.result_channel.status().set_concluded(true);
            if let Ok(result) = result {
                return Some(result);
            }
        }
        None
    }
}