Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid some extra clones/allocations #2865

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 16 additions & 17 deletions axum/src/routing/method_routing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1026,29 +1026,28 @@ 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 RouteFuture::from_future(route.clone().oneshot_inner($req))
.strip_body($method == Method::HEAD);
return RouteFuture::from_future(
route.clone().oneshot_inner_owned($req),
)
.strip_body(Method::$method_variant == Method::HEAD);
}
MethodEndpoint::BoxedHandler(handler) => {
let route = handler.clone().into_route(state);
return RouteFuture::from_future(route.clone().oneshot_inner($req))
.strip_body($method == Method::HEAD);
return RouteFuture::from_future(route.oneshot_inner_owned($req))
.strip_body(Method::$method_variant == Method::HEAD);
}
}
}
};
}

let method = req.method().clone();

// written with a pattern match like this to ensure we call all routes
let Self {
get,
Expand All @@ -1063,15 +1062,15 @@ 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, 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);

let future = fallback.clone().call_with_state(req, state);

Expand Down
8 changes: 4 additions & 4 deletions axum/src/routing/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -656,14 +656,14 @@ where
}
}

fn call_with_state(&mut self, req: Request, state: S) -> RouteFuture<E> {
fn call_with_state(self, req: Request, state: S) -> RouteFuture<E> {
match self {
Fallback::Default(route) | Fallback::Service(route) => {
RouteFuture::from_future(route.oneshot_inner(req))
RouteFuture::from_future(route.oneshot_inner_owned(req))
}
Fallback::BoxedHandler(handler) => {
let mut route = handler.clone().into_route(state);
RouteFuture::from_future(route.oneshot_inner(req))
let route = handler.into_route(state);
RouteFuture::from_future(route.oneshot_inner_owned(req))
}
}
}
Expand Down
16 changes: 10 additions & 6 deletions axum/src/routing/path_router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -331,9 +331,11 @@ where
}
}

let path = req.uri().path().to_owned();
// split apart to get multiple mutable references to parts,
// this avoids the need to clone the URI/path.
let (mut parts, body) = req.into_parts();

match self.node.at(&path) {
match self.node.at(parts.uri.path()) {
Ok(match_) => {
let id = *match_.value;

Expand All @@ -342,22 +344,24 @@ where
crate::extract::matched_path::set_matched_path_for_request(
id,
&self.node.route_id_to_path,
req.extensions_mut(),
&mut parts.extensions,
);
}

url_params::insert_url_params(req.extensions_mut(), match_.params);
url_params::insert_url_params(&mut parts.extensions, match_.params);

let endpoint = self
.routes
.get(&id)
.expect("no route for id. This is a bug in axum. Please file an issue");

let req = Request::from_parts(parts, body);

match endpoint {
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
Expand All @@ -366,7 +370,7 @@ where
MatchError::NotFound
| MatchError::ExtraTrailingSlash
| MatchError::MissingTrailingSlash,
) => Err((req, state)),
) => Err((Request::from_parts(parts, body), state)),
}
}

Expand Down
14 changes: 14 additions & 0 deletions axum/src/routing/route.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,27 @@ impl<E> Route<E> {
)))
}

/// Variant of [`Route::call`] that takes ownership of the route to avoid cloning.
pub(crate) fn call_owned(self, req: Request<Body>) -> RouteFuture<E> {
let req = req.map(Body::new);
RouteFuture::from_future(self.oneshot_inner_owned(req))
}

pub(crate) fn oneshot_inner(
&mut self,
req: Request,
) -> Oneshot<BoxCloneService<Request, Response, E>, Request> {
self.0.get_mut().unwrap().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,
) -> Oneshot<BoxCloneService<Request, Response, E>, Request> {
self.0.into_inner().unwrap().oneshot(req)
}

pub(crate) fn layer<L, NewError>(self, layer: L) -> Route<NewError>
where
L: Layer<Route<E>> + Clone + Send + 'static,
Expand Down
2 changes: 1 addition & 1 deletion axum/src/routing/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -952,7 +952,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]
Expand Down