use futures::Future;
use futures::sync::mpsc::UnboundedSender;
use futures::sync::oneshot;
use serde::Deserialize;
use {Dispatch, Error, Response};
use protocol::{self, Flatten, Primitive};
#[derive(Debug)]
pub struct PrimitiveDispatch<T> {
tx: oneshot::Sender<Result<T, Error>>,
}
impl<T> PrimitiveDispatch<T> {
pub fn new(tx: oneshot::Sender<Result<T, Error>>) -> Self {
Self { tx: tx }
}
pub fn pair() -> (Self, impl Future<Item = T, Error = Error>) {
let (tx, rx) = oneshot::channel();
let result = PrimitiveDispatch::new(tx);
let future = rx.map_err(|e| e.into()).then(|r| r.and_then(|v| v));
(result, future)
}
}
impl<T: for<'de> Deserialize<'de> + Send> Dispatch for PrimitiveDispatch<T> {
fn process(self: Box<Self>, response: &Response) -> Option<Box<Dispatch>> {
let result = response.deserialize::<Primitive<T>>()
.flatten();
drop(self.tx.send(result));
None
}
fn discard(self: Box<Self>, err: &Error) {
drop(self.tx.send(Err(err.clone())));
}
}
#[derive(Debug)]
pub struct StreamingDispatch<T> {
tx: UnboundedSender<Result<T, Error>>,
}
impl<T> StreamingDispatch<T> {
pub fn new(tx: UnboundedSender<Result<T, Error>>) -> Self {
Self { tx: tx }
}
fn send(self: Box<Self>, result: Result<T, Error>) -> Option<Box<Dispatch>>
where T: for<'de> Deserialize<'de> + Send + 'static
{
if self.tx.unbounded_send(result).is_ok() {
Some(self)
} else {
None
}
}
}
impl<T: for<'de> Deserialize<'de> + Send + 'static> Dispatch for StreamingDispatch<T> {
fn process(self: Box<Self>, response: &Response) -> Option<Box<Dispatch>> {
match response.deserialize::<protocol::Streaming<T>>().flatten() {
Ok(Some(data)) => self.send(Ok(data)),
Ok(None) => None,
Err(err) => self.send(Err(err)),
}
}
fn discard(self: Box<Self>, err: &Error) {
drop(self.tx.unbounded_send(Err(err.clone())))
}
}