use crate::communication::Push;
use crate::container::{ContainerBuilder, SizableContainer, PushInto};
use crate::dataflow::channels::Message;
use crate::{Container, Data};
pub struct Exchange<T, CB, P, H>
where
CB: ContainerBuilder,
CB::Container: SizableContainer,
P: Push<Message<T, CB::Container>>,
for<'a> H: FnMut(&<CB::Container as Container>::Item<'a>) -> u64
{
pushers: Vec<P>,
buffers: Vec<CB>,
current: Option<T>,
hash_func: H,
}
impl<T: Clone, CB, P, H> Exchange<T, CB, P, H>
where
CB: ContainerBuilder,
CB::Container: SizableContainer,
P: Push<Message<T, CB::Container>>,
for<'a> H: FnMut(&<CB::Container as Container>::Item<'a>) -> u64
{
pub fn new(pushers: Vec<P>, key: H) -> Exchange<T, CB, P, H> {
let mut buffers = vec![];
for _ in 0..pushers.len() {
buffers.push(Default::default());
}
Exchange {
pushers,
hash_func: key,
buffers,
current: None,
}
}
#[inline]
fn flush(&mut self, index: usize) {
while let Some(container) = self.buffers[index].finish() {
if let Some(ref time) = self.current {
Message::push_at(container, time.clone(), &mut self.pushers[index]);
}
}
}
}
impl<T: Eq+Data, CB, P, H> Push<Message<T, CB::Container>> for Exchange<T, CB, P, H>
where
CB: ContainerBuilder,
CB::Container: SizableContainer,
CB: for<'a> PushInto<<CB::Container as Container>::Item<'a>>,
P: Push<Message<T, CB::Container>>,
for<'a> H: FnMut(&<CB::Container as Container>::Item<'a>) -> u64
{
#[inline(never)]
fn push(&mut self, message: &mut Option<Message<T, CB::Container>>) {
if self.pushers.len() == 1 {
self.pushers[0].push(message);
}
else if let Some(message) = message {
let time = &message.time;
let data = &mut message.data;
if self.current.as_ref().map_or(false, |x| x != time) {
for index in 0..self.pushers.len() {
self.flush(index);
}
}
self.current = Some(time.clone());
let hash_func = &mut self.hash_func;
if self.pushers.len().is_power_of_two() {
let mask = (self.pushers.len() - 1) as u64;
CB::partition(data, &mut self.buffers, |datum| ((hash_func)(datum) & mask) as usize);
}
else {
let num_pushers = self.pushers.len() as u64;
CB::partition(data, &mut self.buffers, |datum| ((hash_func)(datum) % num_pushers) as usize);
}
for (buffer, pusher) in self.buffers.iter_mut().zip(self.pushers.iter_mut()) {
while let Some(container) = buffer.extract() {
Message::push_at(container, time.clone(), pusher);
}
}
}
else {
for index in 0..self.pushers.len() {
self.flush(index);
self.pushers[index].push(&mut None);
}
}
}
}