1use core::any::Any;
4use core::future::{Future, ready};
5use core::pin::Pin;
6use std::rc::Rc;
7
8use crate::error::Rejection;
9use crate::extract::FromRequest;
10use crate::request::Request;
11
12pub(crate) type LocalBoxFuture<T> = Pin<Box<dyn Future<Output = T>>>;
13
14pub(crate) type ErasedHandler<S> =
16 Rc<dyn Fn(&Request, &S) -> LocalBoxFuture<Result<Box<dyn Any>, Rejection>>>;
17
18pub trait Handler<T, S>: 'static {
26 type Output;
27 type Future: Future<Output = Self::Output> + 'static;
28
29 fn call(&self, req: &Request, state: &S) -> Result<Self::Future, Rejection>;
35}
36
37macro_rules! impl_handler {
38 ($($ty:ident),*) => {
39 #[expect(
40 clippy::allow_attributes,
41 reason = "whether the lints fire depends on the arity, so `expect` would be unfulfilled for some"
42 )]
43 impl<F, Fut, S, $($ty,)*> Handler<($($ty,)*), S> for F
44 where
45 F: Fn($($ty),*) -> Fut + 'static,
46 Fut: Future + 'static,
47 $($ty: FromRequest<S>,)*
48 {
49 type Output = Fut::Output;
50 type Future = Fut;
51
52 #[allow(non_snake_case, unused_variables)]
53 fn call(&self, req: &Request, state: &S) -> Result<Fut, Rejection> {
54 $(let $ty = $ty::from_request(req, state)?;)*
55 Ok(self($($ty),*))
56 }
57 }
58 };
59}
60
61crate::all_tuples!(impl_handler);
62
63pub(crate) fn erase<H, T, S, D, E>(handler: H) -> ErasedHandler<S>
65where
66 H: Handler<T, S, Output = Result<D, E>>,
67 D: 'static,
68 E: Into<Rejection>,
69{
70 Rc::new(move |req, state| match handler.call(req, state) {
71 Ok(fut) => Box::pin(async move {
72 fut.await
73 .map(|data| Box::new(data) as Box<dyn Any>)
74 .map_err(Into::into)
75 }),
76 Err(rejection) => Box::pin(ready(Err(rejection))),
77 })
78}
79
80pub(crate) fn unit<S: 'static>() -> ErasedHandler<S> {
82 Rc::new(|_, _| Box::pin(ready(Ok(Box::new(()) as Box<dyn Any>))))
83}