Skip to content

Commit cb20747

Browse files
davidpdrsnjplatte
andauthored
Make Router faster to clone (#1123)
* Make `Router` faster to clone * changelog * Update axum/src/routing/mod.rs Co-authored-by: Jonas Platte <jplatte+git@posteo.de> * fix * Update axum/src/routing/mod.rs Co-authored-by: Jonas Platte <jplatte+git@posteo.de> Co-authored-by: Jonas Platte <jplatte+git@posteo.de>
1 parent 523c7fe commit cb20747

2 files changed

Lines changed: 14 additions & 8 deletions

File tree

axum/CHANGELOG.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
# Unreleased
99

10-
- None.
10+
- **fixed:** Make `Router` cheaper to clone ([#1123])
11+
12+
[#1123]: https://github.com/tokio-rs/axum/pull/1123
1113

1214
# 0.5.9 (20. June, 2022)
1315

axum/src/routing/mod.rs

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ impl RouteId {
6464
/// The router type for composing handlers and services.
6565
pub struct Router<B = Body> {
6666
routes: HashMap<RouteId, Endpoint<B>>,
67-
node: Node,
67+
node: Arc<Node>,
6868
fallback: Fallback<B>,
6969
nested_at_root: bool,
7070
}
@@ -73,7 +73,7 @@ impl<B> Clone for Router<B> {
7373
fn clone(&self) -> Self {
7474
Self {
7575
routes: self.routes.clone(),
76-
node: self.node.clone(),
76+
node: Arc::clone(&self.node),
7777
fallback: self.fallback.clone(),
7878
nested_at_root: self.nested_at_root,
7979
}
@@ -162,9 +162,12 @@ where
162162
Err(service) => Endpoint::Route(Route::new(service)),
163163
};
164164

165-
if let Err(err) = self.node.insert(path, id) {
165+
let mut node =
166+
Arc::try_unwrap(Arc::clone(&self.node)).unwrap_or_else(|node| (*node).clone());
167+
if let Err(err) = node.insert(path, id) {
166168
self.panic_on_matchit_error(err);
167169
}
170+
self.node = Arc::new(node);
168171

169172
self.routes.insert(id, service);
170173

@@ -211,12 +214,12 @@ where
211214
panic!("Cannot nest `Router`s that has a fallback");
212215
}
213216

214-
for (id, nested_path) in node.route_id_to_path {
215-
let route = routes.remove(&id).unwrap();
216-
let full_path: Cow<str> = if &*nested_path == "/" {
217+
for (id, nested_path) in &node.route_id_to_path {
218+
let route = routes.remove(id).unwrap();
219+
let full_path: Cow<str> = if &**nested_path == "/" {
217220
path.into()
218221
} else if path == "/" {
219-
(&*nested_path).into()
222+
(&**nested_path).into()
220223
} else if let Some(path) = path.strip_suffix('/') {
221224
format!("{}{}", path, nested_path).into()
222225
} else {
@@ -632,6 +635,7 @@ impl<B> fmt::Debug for Endpoint<B> {
632635
}
633636

634637
#[test]
638+
#[allow(warnings)]
635639
fn traits() {
636640
use crate::test_helpers::*;
637641
assert_send::<Router<()>>();

0 commit comments

Comments
 (0)