use lossyq::spsc::{Sender, channel};
use super::super::{Task, Message, Schedule, IdentifiedReceiver, new_id, ChannelId};
use super::connectable::{Connectable};
use super::identified_input::{IdentifiedInput};
use super::output_counter::{OutputCounter};
pub trait Scatter {
type InputType : Send;
type OutputType : Send;
fn process(
&mut self,
input: &mut Option<IdentifiedReceiver<Self::InputType>>,
output: &mut Vec<Sender<Message<Self::OutputType>>>) -> Schedule;
}
pub struct ScatterWrap<Input: Send, Output: Send> {
name : String,
state : Box<Scatter<InputType=Input,OutputType=Output>+Send>,
input_rx : Option<IdentifiedReceiver<Input>>,
output_tx_vec : Vec<Sender<Message<Output>>>,
}
impl<Input: Send, Output: Send> IdentifiedInput for ScatterWrap<Input,Output> {
fn get_input_id(&self, ch_id: usize) -> Option<ChannelId> {
if ch_id != 0 {
None
} else {
match &self.input_rx {
&Some(ref ch) => Some(ch.id.clone()),
_ => None,
}
}
}
}
impl<Input: Send, Output: Send> OutputCounter for ScatterWrap<Input,Output> {
fn get_tx_count(&self, ch_id: usize) -> usize {
if ch_id < self.output_tx_vec.len() {
let otx_slice = self.output_tx_vec.as_slice();
otx_slice[ch_id].seqno()
} else {
0
}
}
}
impl<Input: Send, Output: Send> Connectable for ScatterWrap<Input,Output> {
type Input = Input;
fn input(&mut self) -> &mut Option<IdentifiedReceiver<Input>> {
&mut self.input_rx
}
}
impl<Input: Send, Output: Send> Task for ScatterWrap<Input,Output> {
fn execute(&mut self) -> Schedule {
self.state.process(&mut self.input_rx,
&mut self.output_tx_vec)
}
fn name(&self) -> &String { &self.name }
fn input_count(&self) -> usize { 1 }
fn output_count(&self) -> usize { self.output_tx_vec.len() }
fn input_id(&self, ch_id: usize) -> Option<ChannelId> {
self.get_input_id(ch_id)
}
fn tx_count(&self, ch_id: usize) -> usize {
self.get_tx_count(ch_id)
}
}
pub fn new<Input: Send, Output: Send>(
name : &str,
output_q_size : usize,
scatter : Box<Scatter<InputType=Input,OutputType=Output>+Send>,
n_channels : usize)
-> (Box<ScatterWrap<Input,Output>>, Vec<Box<Option<IdentifiedReceiver<Output>>>>)
{
let mut tx_vec = Vec::with_capacity(n_channels);
let mut rx_vec = Vec::with_capacity(n_channels);
for i in 0..n_channels {
let (output_tx, output_rx) = channel(output_q_size);
tx_vec.push(output_tx);
rx_vec.push(
Box::new(
Some(
IdentifiedReceiver{
id: new_id(String::from(name), i),
input: output_rx,
}
)
)
);
}
(
Box::new(
ScatterWrap{
name : String::from(name),
state : scatter,
input_rx : None,
output_tx_vec : tx_vec,
}
),
rx_vec
)
}