matchit/
lib.rs

1/*!
2A high performance, zero-copy URL router.
3
4```rust
5use matchit::Router;
6
7fn main() -> Result<(), Box<dyn std::error::Error>> {
8    let mut router = Router::new();
9    router.insert("/home", "Welcome!")?;
10    router.insert("/users/{id}", "A User")?;
11
12    let matched = router.at("/users/978")?;
13    assert_eq!(matched.params.get("id"), Some("978"));
14    assert_eq!(*matched.value, "A User");
15
16    Ok(())
17}
18```
19
20# Parameters
21
22The router supports dynamic route segments. These can either be named or catch-all parameters.
23
24Named parameters like `/{id}` match anything until the next `/` or the end of the path. Note that named parameters must be followed
25by a `/` or the end of the route. Dynamic suffixes are not currently supported.
26
27```rust
28# use matchit::Router;
29# fn main() -> Result<(), Box<dyn std::error::Error>> {
30let mut m = Router::new();
31m.insert("/users/{id}", true)?;
32
33assert_eq!(m.at("/users/1")?.params.get("id"), Some("1"));
34assert_eq!(m.at("/users/23")?.params.get("id"), Some("23"));
35assert!(m.at("/users").is_err());
36# Ok(())
37# }
38```
39
40Catch-all parameters start with `*` and match anything until the end of the path. They must always be at the **end** of the route.
41
42```rust
43# use matchit::Router;
44# fn main() -> Result<(), Box<dyn std::error::Error>> {
45let mut m = Router::new();
46m.insert("/{*p}", true)?;
47
48assert_eq!(m.at("/foo.js")?.params.get("p"), Some("foo.js"));
49assert_eq!(m.at("/c/bar.css")?.params.get("p"), Some("c/bar.css"));
50
51// note that this will not match
52assert!(m.at("/").is_err());
53# Ok(())
54# }
55```
56
57The literal characters `{` and `}` may be included in a static route by escaping them with the same character. For example, the `{` character is escaped with `{{` and the `}` character is escaped with `}}`.
58
59```rust
60# use matchit::Router;
61# fn main() -> Result<(), Box<dyn std::error::Error>> {
62let mut m = Router::new();
63m.insert("/{{hello}}", true)?;
64m.insert("/{hello}", true)?;
65
66// match the static route
67assert!(m.at("/{hello}")?.value);
68
69// match the dynamic route
70assert_eq!(m.at("/hello")?.params.get("hello"), Some("hello"));
71# Ok(())
72# }
73```
74
75# Routing Priority
76
77Static and dynamic route segments are allowed to overlap. If they do, static segments will be given higher priority:
78
79```rust
80# use matchit::Router;
81# fn main() -> Result<(), Box<dyn std::error::Error>> {
82let mut m = Router::new();
83m.insert("/", "Welcome!").unwrap();      // priority: 1
84m.insert("/about", "About Me").unwrap(); // priority: 1
85m.insert("/{*filepath}", "...").unwrap();  // priority: 2
86# Ok(())
87# }
88```
89
90# How does it work?
91
92The router takes advantage of the fact that URL routes generally follow a hierarchical structure. Routes are stored them in a radix trie that makes heavy use of common prefixes.
93
94```text
95Priority   Path             Value
969          \                1
973          ├s               None
982          |├earch\         2
991          |└upport\        3
1002          ├blog\           4
1011          |    └{post}     None
1021          |          └\    5
1032          ├about-us\       6
1041          |        └team\  7
1051          └contact\        8
106```
107
108This allows us to reduce the route search to a small number of branches. Child nodes on the same level of the tree are also prioritized
109by the number of children with registered values, increasing the chance of choosing the correct branch of the first try.
110
111As it turns out, this method of routing is extremely fast. See the [benchmark results](https://github.com/ibraheemdev/matchit?tab=readme-ov-file#benchmarks) for details.
112*/
113
114#![deny(rust_2018_idioms, clippy::all)]
115
116mod error;
117mod escape;
118mod params;
119mod router;
120mod tree;
121
122pub use error::{InsertError, MatchError};
123pub use params::{Params, ParamsIter};
124pub use router::{Match, Router};
125
126#[cfg(doctest)]
127mod readme {
128    #[allow(dead_code)]
129    #[doc = include_str!("../README.md")]
130    struct Readme;
131}