use core::any::Any;
use core::future::{Future, ready};
use core::pin::Pin;
use std::rc::Rc;
use crate::error::Rejection;
use crate::extract::FromRequest;
use crate::request::Request;
pub(crate) type LocalBoxFuture<T> = Pin<Box<dyn Future<Output = T>>>;
pub(crate) type ErasedHandler<S> =
Rc<dyn Fn(&Request, &S) -> LocalBoxFuture<Result<Box<dyn Any>, Rejection>>>;
pub trait Handler<T, S>: 'static {
type Output;
type Future: Future<Output = Self::Output> + 'static;
fn call(&self, req: &Request, state: &S) -> Result<Self::Future, Rejection>;
}
macro_rules! impl_handler {
($($ty:ident),*) => {
#[expect(
clippy::allow_attributes,
reason = "whether the lints fire depends on the arity, so `expect` would be unfulfilled for some"
)]
impl<F, Fut, S, $($ty,)*> Handler<($($ty,)*), S> for F
where
F: Fn($($ty),*) -> Fut + 'static,
Fut: Future + 'static,
$($ty: FromRequest<S>,)*
{
type Output = Fut::Output;
type Future = Fut;
#[allow(non_snake_case, unused_variables)]
fn call(&self, req: &Request, state: &S) -> Result<Fut, Rejection> {
$(let $ty = $ty::from_request(req, state)?;)*
Ok(self($($ty),*))
}
}
};
}
crate::all_tuples!(impl_handler);
pub(crate) fn erase<H, T, S, D, E>(handler: H) -> ErasedHandler<S>
where
H: Handler<T, S, Output = Result<D, E>>,
D: 'static,
E: Into<Rejection>,
{
Rc::new(move |req, state| match handler.call(req, state) {
Ok(fut) => Box::pin(async move {
fut.await
.map(|data| Box::new(data) as Box<dyn Any>)
.map_err(Into::into)
}),
Err(rejection) => Box::pin(ready(Err(rejection))),
})
}
pub(crate) fn unit<S: 'static>() -> ErasedHandler<S> {
Rc::new(|_, _| Box::pin(ready(Ok(Box::new(()) as Box<dyn Any>))))
}