avoid one state clone

This is an extraction of a part of https://github.com/tokio-rs/axum/pull/2865
This commit is contained in:
novacrazy 2024-10-09 22:16:18 +02:00 committed by Yann Simon
parent 19b99ea917
commit b363354eaa
3 changed files with 21 additions and 18 deletions

View file

@ -1101,27 +1101,24 @@ where
macro_rules! call {
(
$req:expr,
$method:expr,
$method_variant:ident,
$svc:expr
) => {
if $method == Method::$method_variant {
if *req.method() == Method::$method_variant {
match $svc {
MethodEndpoint::None => {}
MethodEndpoint::Route(route) => {
return route.clone().oneshot_inner($req);
return route.clone().oneshot_inner_owned($req);
}
MethodEndpoint::BoxedHandler(handler) => {
let mut route = handler.clone().into_route(state);
return route.oneshot_inner($req);
let route = handler.clone().into_route(state);
return route.oneshot_inner_owned($req);
}
}
}
};
}
let method = req.method().clone();
// written with a pattern match like this to ensure we call all routes
let Self {
get,
@ -1137,16 +1134,16 @@ where
allow_header,
} = self;
call!(req, method, HEAD, head);
call!(req, method, HEAD, get);
call!(req, method, GET, get);
call!(req, method, POST, post);
call!(req, method, OPTIONS, options);
call!(req, method, PATCH, patch);
call!(req, method, PUT, put);
call!(req, method, DELETE, delete);
call!(req, method, TRACE, trace);
call!(req, method, CONNECT, connect);
call!(req, HEAD, head);
call!(req, HEAD, get);
call!(req, GET, get);
call!(req, POST, post);
call!(req, OPTIONS, options);
call!(req, PATCH, patch);
call!(req, PUT, put);
call!(req, DELETE, delete);
call!(req, TRACE, trace);
call!(req, CONNECT, connect);
let future = fallback.clone().call_with_state(req, state);

View file

@ -47,6 +47,12 @@ impl<E> Route<E> {
RouteFuture::new(method, self.0.clone().oneshot(req))
}
/// Variant of [`Route::oneshot_inner`] that takes ownership of the route to avoid cloning.
pub(crate) fn oneshot_inner_owned(self, req: Request) -> RouteFuture<E> {
let method = req.method().clone();
RouteFuture::new(method, self.0.oneshot(req))
}
pub(crate) fn layer<L, NewError>(self, layer: L) -> Route<NewError>
where
L: Layer<Route<E>> + Clone + Send + 'static,

View file

@ -941,7 +941,7 @@ async fn state_isnt_cloned_too_much() {
client.get("/").await;
assert_eq!(COUNT.load(Ordering::SeqCst), 4);
assert_eq!(COUNT.load(Ordering::SeqCst), 3);
}
#[crate::test]