Wildcard Trie
A space-efficient radix trie implementation for URL routing with wildcard support in Rust. This crate provides fast path lookups with DoS attack resistance by compressing paths and preventing excessive node creation.
Features
- Wildcard Support: Routes ending in
/*match any sub-path - Fast Lookups:
O(path_length)instead ofO(number_of_routes) - DoS Resistant: Long paths don't create excessive nodes due to path compression
- Memory Efficient: Common prefixes are shared (e.g.,
/api/v1/usersand/api/v1/postsshare/api/v1/) - Debug Visualization: Pretty-print trie structure for debugging (with
debugfeature)
Example
Add this to your Cargo.toml:
[]
= "0.1.0"
Then use it in your code:
use Trie;
let mut trie = new;
// Insert routes
trie.insert; // Wildcard route
trie.insert; // Exact route (takes precedence)
trie.insert;
// Lookup routes
assert_eq!; // Exact match
assert_eq!; // Wildcard match
assert_eq!;
// Remove routes
trie.remove;
assert_eq!; // Falls back to wildcard
API Reference
Trie<T>
Methods
new() -> Self- Creates an empty trieinsert(&mut self, path: &str, value: T)- Inserts a value at the given pathget(&self, path: &str) -> Option<&T>- Retrieves a value for the pathremove(&mut self, path: &str) -> Option<T>- Removes and returns a value
Debug Features
When compiled with the debug feature (enabled by default):
pretty_print(&self) -> String- Returns a tree visualization of the trie structure
let mut trie = new;
trie.insert;
trie.insert;
println!;
Examples
URL Routing
use Trie;
let mut router = new;
// Set up routes
router.insert;
router.insert;
router.insert;
router.insert;
router.insert;
// Route requests
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Path Compression Demonstration
The trie automatically compresses common prefixes:
let mut trie = new;
// These routes share the "/api/v1/" prefix
trie.insert;
trie.insert;
trie.insert;
// Only creates nodes for:
// - "/api/v1/" (shared prefix)
// - "users", "posts", "comments" (suffixes)
Features
Default Features
debug- Enables pretty-printing functionality
It may be useful to disable the debug feature for code size:
[]
= { = "0.1.0", = false }
How It Works
The crate uses a radix trie (compressed trie) structure where:
-
Common prefixes are stored in single nodes
/api/v1/usersand/api/v1/postsshare the/api/v1/prefix- Prevents DoS attacks from extremely long segmented paths
-
Routes ending with
/*act as fallbacks- Exact matches take precedence over wildcards
- Wildcards are inherited down the tree for nested matching
-
Each node stores:
- A compressed path prefix
- Optional exact match value
- Optional wildcard match value
- Child nodes indexed by first character