Skip to content

Commit

Permalink
refactor Router::merge
Browse files Browse the repository at this point in the history
  • Loading branch information
ibraheemdev committed Nov 7, 2024
1 parent 7e422d9 commit 1bbb0f2
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
8 changes: 6 additions & 2 deletions src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,11 @@ impl<T> Router<T> {
}

/// Merge a given router into current one.
///
/// Returns a list of [`InsertError`] for every failed insertion.
/// Note that this can result in a partially successful merge if
/// a subset of routes conflict.
///
/// # Examples
///
/// ```rust
Expand All @@ -154,13 +158,13 @@ impl<T> Router<T> {
/// # }
/// ```
pub fn merge(&mut self, other: Self) -> Result<(), MergeError> {
let mut errors = vec![];
let mut errors = Vec::new();
other.root.for_each(|path, value| {
if let Err(err) = self.insert(path, value) {
errors.push(err);
}
true
});

if errors.is_empty() {
Ok(())
} else {
Expand Down
11 changes: 7 additions & 4 deletions src/tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -664,16 +664,19 @@ impl<T> Node<T> {
impl<T> Node<T> {
/// Iterates over the tree and calls the given visitor function
/// with fully resolved path and its value.
pub fn for_each<V: FnMut(String, T) -> bool>(self, mut visitor: V) {
pub fn for_each<V: FnMut(String, T)>(self, mut visitor: V) {
let mut queue = VecDeque::from([(self.prefix.clone(), self)]);

// Perform a BFS on the routing tree.
while let Some((mut prefix, mut node)) = queue.pop_front() {
denormalize_params(&mut prefix, &node.remapping);

if let Some(value) = node.value.take() {
let path = String::from_utf8(prefix.unescaped().to_vec()).unwrap();
if !visitor(path, value.into_inner()) {
return;
}
visitor(path, value.into_inner());
}

// Traverse the child nodes.
for child in node.children {
let mut prefix = prefix.clone();
prefix.append(&child.prefix);
Expand Down

0 comments on commit 1bbb0f2

Please sign in to comment.