Skip to content

feat: add at_or_default to modify exist route #50

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
34 changes: 31 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ impl Index<&str> for Params {
type Output = String;
fn index(&self, index: &str) -> &String {
match self.map.get(index) {
None => panic!(format!("params[{}] did not exist", index)),
None => panic!("params[{}] did not exist", index),
Some(s) => s,
}
}
Expand Down Expand Up @@ -251,7 +251,12 @@ impl<T> Router<T> {
}

/// Add a route to the router.
pub fn add(&mut self, mut route: &str, dest: T) {
pub fn add(&mut self, route: &str, dest: T) {
let state = self.add_state(route);
self.handlers.insert(state, dest);
}

fn add_state(&mut self, mut route: &str) -> usize {
if !route.is_empty() && route.as_bytes()[0] == b'/' {
route = &route[1..];
}
Expand Down Expand Up @@ -281,7 +286,8 @@ impl<T> Router<T> {

nfa.acceptance(state);
nfa.metadata(state, metadata);
self.handlers.insert(state, dest);

state
}

/// Match a route on the router.
Expand Down Expand Up @@ -314,6 +320,15 @@ impl<T> Router<T> {
}
}

impl<T: Default> Router<T> {
/// Returns a mutable reference to the route in the router by inserting the default value if empty.
pub fn at_or_default(&mut self, route: &str) -> &mut T {
let state = self.add_state(route);

self.handlers.entry(state).or_default()
}
}

impl<T> Default for Router<T> {
fn default() -> Self {
Self::new()
Expand Down Expand Up @@ -571,4 +586,17 @@ mod tests {
"Hello"
);
}

#[test]
fn add_or_update_with() {
let mut router = Router::new();

router.add("/hello", vec!["GET".to_string()]);
router.at_or_default("/hello").push("POST".to_string());

let m = router.recognize("/hello").unwrap();

assert_eq!(*m.handler, vec!["GET".to_string(), "POST".to_string()]);
assert_eq!(m.params, Params::new());
}
}