• Stars
    star
    311
  • Rank 130,123 (Top 3 %)
  • Language
    Rust
  • License
    MIT License
  • Created over 3 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A high performance, zero-copy URL router.

matchit

Documentation Version License

A blazing fast URL router.

use matchit::Router;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut router = Router::new();
    router.insert("/home", "Welcome!")?;
    router.insert("/users/:id", "A User")?;

    let matched = router.at("/users/978")?;
    assert_eq!(matched.params.get("id"), Some("978"));
    assert_eq!(*matched.value, "A User");

    Ok(())
}

Parameters

Along with static routes, the router also supports dynamic route segments. These can either be named or catch-all parameters:

Named Parameters

Named parameters like /:id match anything until the next / or the end of the path:

let mut m = Router::new();
m.insert("/users/:id", true)?;

assert_eq!(m.at("/users/1")?.params.get("id"), Some("1"));
assert_eq!(m.at("/users/23")?.params.get("id"), Some("23"));
assert!(m.at("/users").is_err());

Catch-all Parameters

Catch-all parameters start with * and match everything after the /. They must always be at the end of the route:

let mut m = Router::new();
m.insert("/*p", true)?;

assert_eq!(m.at("/foo.js")?.params.get("p"), Some("foo.js"));
assert_eq!(m.at("/c/bar.css")?.params.get("p"), Some("c/bar.css"));

// note that this would not match:
assert_eq!(m.at("/").is_err());

Routing Priority

Static and dynamic route segments are allowed to overlap. If they do, static segments will be given higher priority:

let mut m = Router::new();
m.insert("/", "Welcome!").unwrap();      // priority: 1
m.insert("/about", "About Me").unwrap(); // priority: 1
m.insert("/*filepath", "...").unwrap();  // priority: 2

How does it work?

The 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:

Priority   Path             Value
9          \                1
3          ├s               None
2          |├earch\         2
1          |â””upport\        3
2          ├blog\           4
1          |    â””:post      None
1          |         â””\     5
2          ├about-us\       6
1          |        â””team\  7
1          â””contact\        8

This 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 by the number of children with registered values, increasing the chance of choosing the correct branch of the first try.

Benchmarks

As it turns out, this method of routing is extremely fast. In a benchmark matching 4 paths against 130 registered routes, matchit find the correct routes in under 200 nanoseconds, an order of magnitude faster than most other routers. You can view the benchmark code here.

Compare Routers/matchit 
time:   [197.57 ns 198.74 ns 199.83 ns]

Compare Routers/actix
time:   [26.805 us 26.811 us 26.816 us]

Compare Routers/path-tree
time:   [468.95 ns 470.34 ns 471.65 ns]

Compare Routers/regex
time:   [22.539 us 22.584 us 22.639 us]

Compare Routers/route-recognizer
time:   [3.7552 us 3.7732 us 3.8027 us]

Compare Routers/routefinder
time:   [5.7313 us 5.7405 us 5.7514 us]

Credits

A lot of the code in this package was based on Julien Schmidt's httprouter.

More Repositories

1

modern-unix

A collection of modern/faster/saner alternatives to common unix commands.
29,534
star
2

seize

Fast, efficient, and robust memory reclamation for Rust.
Rust
299
star
3

astra

Rust web servers without async/await.
Rust
161
star
4

boxcar

A concurrent, append-only vector.
Rust
100
star
5

too-many-web-servers

https://ibraheem.ca/posts/too-many-web-servers/
Rust
80
star
6

awaitgroup

Wait for a collection of async tasks to finish.
Rust
28
star
7

dotfiles

My dotfiles for zsh, vim, i3, polybar, alacritty ...
Lua
24
star
8

httprouter-rs

A fast, minimal HTTP framework.
Rust
16
star
9

ripc

A C compiler, written in Rust.
Rust
9
star
10

firefly

High performance concurrent channels.
Rust
6
star
11

derive-alias

Alias mutliple derives as one.
Rust
6
star
12

jiffy

Rust
4
star
13

platoon

A lightweight async runtime for Rust.
Rust
4
star
14

mongo_beautiful_logger

A simple and beautiful logger gem for MongoDB in you Ruby/Rails app.
Ruby
4
star
15

agilely

Agilely is an open source project management solution for individuals and teams alike.
Ruby
4
star
16

bison

A powerful web-application framework that does the heavy lifting for you.
Rust
2
star
17

ibraheemdev

Ibraheem Ahmed | Software developer. Open source enthusiast. Freelancer.
SCSS
1
star
18

turbofish

A fast, executor agnostic HTTP implementation in Rust.
Rust
1
star
19

go-chatrooms-example

This application shows how to use the websocket package to implement a simple web chat application with multiple rooms
Go
1
star
20

seize-hashmap

A Rust concurrent HashMap optimized for read-heavy workloads.
Rust
1
star
21

tictactoe

A react powered tictactoe app
JavaScript
1
star
22

papaya-db

Rust
1
star
23

dangerous-shell-commands

1
star