From af95794e7d70bf61132b87b4a4614a9571c5413b Mon Sep 17 00:00:00 2001 From: novacrazy Date: Thu, 10 Oct 2024 11:35:04 +0200 Subject: [PATCH] avoid cloning the state in layer --- axum/src/routing/path_router.rs | 2 +- axum/src/routing/route.rs | 6 ++++++ axum/src/routing/tests/mod.rs | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/axum/src/routing/path_router.rs b/axum/src/routing/path_router.rs index c3ee0412..fafb2882 100644 --- a/axum/src/routing/path_router.rs +++ b/axum/src/routing/path_router.rs @@ -394,7 +394,7 @@ where Endpoint::MethodRouter(method_router) => { Ok(method_router.call_with_state(req, state)) } - Endpoint::Route(route) => Ok(route.clone().call(req)), + Endpoint::Route(route) => Ok(route.clone().call_owned(req)), } } // explicitly handle all variants in case matchit adds diff --git a/axum/src/routing/route.rs b/axum/src/routing/route.rs index 1724c30a..03e2bd6b 100644 --- a/axum/src/routing/route.rs +++ b/axum/src/routing/route.rs @@ -42,6 +42,12 @@ impl Route { )) } + /// Variant of [`Route::call`] that takes ownership of the route to avoid cloning. + pub(crate) fn call_owned(self, req: Request) -> RouteFuture { + let req = req.map(Body::new); + self.oneshot_inner_owned(req).not_top_level() + } + pub(crate) fn oneshot_inner(&mut self, req: Request) -> RouteFuture { let method = req.method().clone(); RouteFuture::new(method, self.0.clone().oneshot(req)) diff --git a/axum/src/routing/tests/mod.rs b/axum/src/routing/tests/mod.rs index af8dca1f..84e93898 100644 --- a/axum/src/routing/tests/mod.rs +++ b/axum/src/routing/tests/mod.rs @@ -942,7 +942,7 @@ async fn state_isnt_cloned_too_much_in_layer() { client.get("/").await; - assert_eq!(state.count(), 4); + assert_eq!(state.count(), 3); } #[crate::test]