use futures::IntoFuture;
use std::sync::Arc;
use super::{BoxFutureResponse, BoxHandler, Context, Handler, Response};
pub struct Stack {
root: Arc<BoxHandler>,
elements: Vec<BoxStackBoxHandler>,
}
impl Stack {
pub fn new<H: Handler + 'static>(root: H) -> Self {
Stack {
root: Arc::new(root.boxed()),
elements: Vec::new(),
}
}
pub fn add<T: StackHandler + 'static>(&mut self, handler: T) {
self.elements.push(boxed(handler));
}
}
impl Handler for Stack {
type Result = BoxFutureResponse;
#[inline]
fn call(&self, ctx: Context) -> Self::Result {
let root = self.root.clone();
let mut next = Box::new(move |ctx| root.call(ctx)) as BoxHandler;
for element in self.elements.iter().rev() {
next = element.call(next);
}
next.call(ctx)
}
}
pub trait StackHandler: Send + Sync {
type Handler: Handler + 'static;
fn call(&self, next: BoxHandler) -> Self::Handler;
}
impl<TError, TFuture, THandler, TFn> StackHandler for TFn
where
TFuture: IntoFuture<Item = Response, Error = TError>,
THandler: Handler<Result = TFuture>,
THandler: 'static,
TFn: Send + Sync,
TFn: Fn(BoxHandler) -> THandler,
{
type Handler = THandler;
#[inline]
fn call(&self, next: BoxHandler) -> Self::Handler {
(*self)(next)
}
}
trait StackBoxHandler: Send + Sync {
fn call(&self, next: BoxHandler) -> BoxHandler;
}
impl<TFn> StackBoxHandler for TFn
where
TFn: Send + Sync,
TFn: Fn(BoxHandler) -> BoxHandler,
{
#[inline]
fn call(&self, next: BoxHandler) -> BoxHandler {
(*self)(next)
}
}
type BoxStackBoxHandler = Box<StackBoxHandler>;
fn boxed<H: StackHandler + 'static>(handler: H) -> BoxStackBoxHandler {
Box::new(move |next: BoxHandler| handler.call(next).boxed())
}