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

feat(router): add merge function #62

Merged
merged 5 commits into from
Oct 14, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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: 33 additions & 0 deletions src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,39 @@ impl<T> Router<T> {
pub fn check_priorities(&self) -> Result<u32, (u32, u32)> {
self.root.check_priorities()
}


/// Merge a given router into current one.
darkenmay marked this conversation as resolved.
Show resolved Hide resolved
///
///
/// # Examples
///
/// ```rust
/// # use matchit::Router;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut root = Router::new();
/// root.insert("/home", "Welcome!")?;
///
/// let mut child = Router::new();
/// child.insert("/users/{id}", "A User")?;
///
/// root.merge(child)?;
darkenmay marked this conversation as resolved.
Show resolved Hide resolved
/// # Ok(())
/// # }
/// ```
pub fn merge(&mut self, other: Self) -> Result<(), InsertError> {
let mut result = Ok(());
other.root.for_each(|path, value| {
match self.insert(path, value) {
Ok(..) => true,
Err(err) => {
result = Err(err);
false
darkenmay marked this conversation as resolved.
Show resolved Hide resolved
}
}
});
result
}
}

/// A successful match consisting of the registered value
Expand Down
27 changes: 27 additions & 0 deletions src/tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use crate::{InsertError, MatchError, Params};

use std::cell::UnsafeCell;
use std::cmp::min;
use std::collections::VecDeque;
use std::ops::Range;
use std::{fmt, mem};

Expand Down Expand Up @@ -660,6 +661,32 @@ 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) {
let mut queue = VecDeque::new();
queue.push_back(self);
while let Some(mut node) = queue.pop_front() {
if node.children.is_empty() {
denormalize_params(&mut node.prefix, &node.remapping);
let path = String::from_utf8(node.prefix.into_unescaped()).unwrap();
let value = node.value.take().map(UnsafeCell::into_inner);
if !visitor(path, value.unwrap()) {
return;
}
} else {
darkenmay marked this conversation as resolved.
Show resolved Hide resolved
for mut child in node.children {
let mut prefix = node.prefix.clone();
prefix.append(&child.prefix);
child.prefix = prefix;
darkenmay marked this conversation as resolved.
Show resolved Hide resolved
queue.push_front(child);
}
}
}
}
}

/// An ordered list of route parameters keys for a specific route.
///
/// To support conflicting routes like `/{a}/foo` and `/{b}/bar`, route parameters
Expand Down
30 changes: 30 additions & 0 deletions tests/merge.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use matchit::{InsertError, Router};

#[test]
fn merge_ok() {
let mut root = Router::new();
assert!(root.insert("/foo", "foo").is_ok());
assert!(root.insert("/bar/{id}", "bar").is_ok());

let mut child = Router::new();
assert!(child.insert("/baz", "baz").is_ok());
assert!(child.insert("/xyz/{id}", "xyz").is_ok());

assert!(root.merge(child).is_ok());

assert_eq!(root.at("/foo").map(|m| *m.value), Ok("foo"));
assert_eq!(root.at("/bar/1").map(|m| *m.value), Ok("bar"));
assert_eq!(root.at("/baz").map(|m| *m.value), Ok("baz"));
assert_eq!(root.at("/xyz/2").map(|m| *m.value), Ok("xyz"));
}

#[test]
fn merge_conflict() {
let mut root = Router::new();
assert!(root.insert("/foo", "foo").is_ok());

let mut child = Router::new();
assert!(child.insert("/foo", "foo").is_ok());

assert_eq!(root.merge(child), Err(InsertError::Conflict {with: "/foo".into()}));
}
Loading