axum/src/clone_box_service.rs
David Pedersen 0ee7379d4f
Fix compile time regression by boxing routes internally (#404)
This is a reimplementation of #401 but with the new matchit based router.

Fixes #399
2021-10-24 20:52:42 +02:00

64 lines
1.6 KiB
Rust

use futures_util::future::BoxFuture;
use std::task::{Context, Poll};
use tower::ServiceExt;
use tower_service::Service;
/// A `Clone + Send` boxed `Service`
pub(crate) struct CloneBoxService<T, U, E>(
Box<
dyn CloneService<T, Response = U, Error = E, Future = BoxFuture<'static, Result<U, E>>>
+ Send,
>,
);
impl<T, U, E> CloneBoxService<T, U, E> {
pub(crate) fn new<S>(inner: S) -> Self
where
S: Service<T, Response = U, Error = E> + Clone + Send + 'static,
S::Future: Send + 'static,
{
let inner = inner.map_future(|f| Box::pin(f) as _);
CloneBoxService(Box::new(inner))
}
}
impl<T, U, E> Service<T> for CloneBoxService<T, U, E> {
type Response = U;
type Error = E;
type Future = BoxFuture<'static, Result<U, E>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), E>> {
self.0.poll_ready(cx)
}
fn call(&mut self, request: T) -> Self::Future {
self.0.call(request)
}
}
impl<T, U, E> Clone for CloneBoxService<T, U, E> {
fn clone(&self) -> Self {
Self(self.0.clone_box())
}
}
trait CloneService<R>: Service<R> {
fn clone_box(
&self,
) -> Box<
dyn CloneService<R, Response = Self::Response, Error = Self::Error, Future = Self::Future>
+ Send,
>;
}
impl<R, T> CloneService<R> for T
where
T: Service<R> + Send + Clone + 'static,
{
fn clone_box(
&self,
) -> Box<dyn CloneService<R, Response = T::Response, Error = T::Error, Future = T::Future> + Send>
{
Box::new(self.clone())
}
}