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

mod sdf;
#[cfg(test)]
mod test;

pub use self::sdf::ShortestDeadlineFirst;

use super::{StatusBit, RunningTask};

use std::sync::{Mutex, RwLock, Arc};
use std::collections::VecDeque;

use atomicmonitor::AtomMonitor;
use atomicmonitor::atomic::{Atomic, Ordering};

use futures::Future;

/// A channel by which futures becomes available to the thread pool.
pub trait Channel {
    fn assign_bits(&mut self, assigner: &mut BitAssigner) -> Result<(), NotEnoughBits>;

    fn poll(&self) -> Option<RunningTask>;

    /// Wrap self in a reference counted read/write lock, which is still a channel,
    /// and can have shared ownership, allowing it to be used in a scheduler.
    fn into_shared(self) -> Arc<RwLock<Self>> where Self: Sized {
        Arc::new(RwLock::new(self))
    }
}

/// A struct used by pools to dispatch up to 64 present bitfield bits to channels.
pub struct BitAssigner<'a, 'b> {
    monitor: &'a Arc<AtomMonitor<u64>>,
    index: &'b mut usize
}
impl<'a, 'b> BitAssigner<'a, 'b> {
    pub fn new(monitor: &'a Arc<AtomMonitor<u64>>, index: &'b mut usize) -> Self {
        BitAssigner {
            monitor,
            index
        }
    }

    pub fn current_index(&self) -> usize {
        *self.index
    }

    pub fn assign(&mut self, bit: &mut StatusBit) -> Result<(), NotEnoughBits> {
        let curr_index = *self.index;
        if curr_index < 64 {
            *self.index += 1;
            bit.activate(self.monitor.clone(), curr_index).ok().unwrap();
            Ok(())
        } else {
            Err(NotEnoughBits)
        }
    }
}

#[derive(Debug)]
pub struct NotEnoughBits;

/// Trait for channels for which a task can be submitted.
pub trait Exec {
    fn exec(&self, future: impl Future<Item=(), Error=()> + Send + 'static) {
        self.submit(RunningTask::new(future));
    }

    fn submit(&self, task: RunningTask);
}

/// Trait for channels for which a task can be submitted along side an additional parameter.
pub trait ExecParam {
    type Param;

    fn exec(&self, future: impl Future<Item=(), Error=()> + Send + 'static, param: Self::Param) {
        self.submit(RunningTask::new(future), param);
    }

    fn submit(&self, task: RunningTask, param: Self::Param);
}

/// Shared channel implementation.
impl<C: Channel> Channel for Arc<RwLock<C>> {
    fn assign_bits(&mut self, assigner: &mut BitAssigner) -> Result<(), NotEnoughBits> {
        let mut guard = self.write().unwrap();
        guard.assign_bits(assigner)
    }

    fn poll(&self) -> Option<RunningTask> {
        let guard = self.read().unwrap();
        guard.poll()
    }
}

/// Shared exec implementation.
impl<E: Exec> Exec for Arc<RwLock<E>> {
    fn submit(&self, task: RunningTask) {
        let guard = self.read().unwrap();
        guard.submit(task);
    }
}

/// Shared exec param implementation.
impl<E: ExecParam> ExecParam for Arc<RwLock<E>> {
    type Param = E::Param;

    fn submit(&self, task: RunningTask, param: E::Param) {
        let guard = self.read().unwrap();
        guard.submit(task, param);
    }
}

/// A simple FIFO channel.
pub struct VecDequeChannel {
    queue: Mutex<VecDeque<RunningTask>>,
    bit: StatusBit
}
impl VecDequeChannel {
    pub fn new() -> Self {
        VecDequeChannel {
            queue: Mutex::new(VecDeque::new()),
            bit: StatusBit::new()
        }
    }
}
impl Exec for VecDequeChannel {
    fn submit(&self, task: RunningTask) {
        let mut guard = self.queue.lock().unwrap();
        guard.push_front(task);
        self.bit.set(true);
    }
}
impl Channel for VecDequeChannel {
    fn assign_bits(&mut self, assigner: &mut BitAssigner) -> Result<(), NotEnoughBits> {
        assigner.assign(&mut self.bit)?;
        self.bit.set(!self.queue.get_mut().unwrap().is_empty());
        Ok(())
    }

    fn poll(&self) -> Option<RunningTask> {
        let mut guard = self.queue.lock().unwrap();
        let future = guard.pop_back();
        self.bit.set(!guard.is_empty());
        future
    }
}

/// A round-robin multi channel wrapper.
pub struct MultiChannel<Inner: Channel> {
    inner: Vec<Inner>,
    index: Atomic<usize>,
}
impl<Inner: Channel> MultiChannel<Inner> {
    pub fn from_vec(inner: Vec<Inner>) -> Self {
        MultiChannel {
            inner,
            index: Atomic::new(0)
        }
    }

    pub fn new(count: usize, factory: impl Fn() -> Inner) -> Self {
        let mut vec = Vec::new();
        for _ in 0..count {
            vec.push(factory());
        }
        Self::from_vec(vec)
    }

    fn index(&self) -> usize {
        self.index.fetch_add(1, Ordering::SeqCst) % self.inner.len()
    }
}
impl<Inner: Channel + Exec> Exec for MultiChannel<Inner> {
    fn submit(&self, task: RunningTask) {
        self.inner[self.index()].submit(task);
    }
}
impl<Inner: Channel + ExecParam> ExecParam for MultiChannel<Inner> {
    type Param = Inner::Param;

    fn submit(&self, task: RunningTask, param: <Self as ExecParam>::Param) {
        self.inner[self.index()].submit(task, param);
    }
}
impl<Inner: Channel> Channel for MultiChannel<Inner> {
    fn assign_bits(&mut self, assigner: &mut BitAssigner) -> Result<(), NotEnoughBits> {
        for inner_channel in &mut self.inner {
            inner_channel.assign_bits(assigner)?;
        }
        Ok(())
    }

    fn poll(&self) -> Option<RunningTask> {
        // Poll from an index as many times as we have inner channels, returning the first one found.
        // (This iterator combination is expected to short circuit).
        (0..self.inner.len())
            .filter_map(|_| self.inner[self.index()].poll())
            .next()
    }
}