prefix_tree_map
A Rust implementation of generic prefix tree (trie) map with wildcard capture support.
Design
Trie is a good data structure for storing key-value pairs with wildcard support ability.
This prefix tree map implementation supports any type of key and value, as long as key parts are implemented the Ord and Clone trait. Internally, nodes are stored in a sorted Vec. So technically it can achieve O(log n) time complexity on finding every node by using binary search on the sorted Vec.
Using as a route-table-like structure could be the best scenario for this crate.
Pros and Cons
Pros
- Fast and efficient
- Wildcard Capture Support - Capture wildcard characters in a map while matching.
- Generalization - Supports any type of key and value, as long as key parts are implemented the
OrdandClonetrait. - Capture Map Customization - Customize the way key parts captured by wildcard stored.
- No recursion in find operations - Rather than store the whole context of every node searching, this prefix tree map only store those tiny wildcard node pointers for backtracking on heap.
Cons
- The map itself is immutable, because the map builder is using Binary Heap to sort the nodes when they are inserted. We can't get a item from a Binary Heap without iterating the whole Binary Heap. Once the
build()is called, Binary Heaps are converted into sortedVecs. We can't push any item to theVecwithout a whole sort operation. - Currently, a single wildcard cannot be matched more than one time. It means
wordcan be matched byw**d, notw*d.
Usage
use PrefixTreeMapBuilder;
let mut map_builder = new;
// To insert an exact key path, call `insert_exact()`
map_builder.insert_exact;
// Insert into a existed key path could overwrite the value in it
map_builder.insert_exact;
// To insert an key path with wildcards, mark key parts using `prefix_tree_map::KeyPart` and call `insert()`
use KeyPart;
map_builder.insert;
// Anything implemented trait `FromIterator` can be inserted as a key path:
let path = "path/to/anothor/value";
map_builder.insert_exact;
let anothor_path = "path/to/:some/value";
map_builder.insert;
// Then build the map
let map = map_builder.build;
// Find a value without matching any wildcard part
assert_eq!;
// Find a value with matching wildcard part
assert_eq!;
// `KeyPart::Exact` has a higher match priority than `KeyPart::Wildcard`
assert_eq!;
// Find a value with matching wildcard part, and store captured matched wildcard parts in a map
use HashMap;
let mut captures = new;
assert_eq!;
assert_eq!;
Customizing Capture map:
use Captures;
For more infomation, check out examples/router.rs
no_std
Opt out the std feature by disabling default-features in Cargo.toml to remove the Rust standard library dependency.
Examples
Check examples.
License
GNU General Public License v3.0