| Crates.io | token_trie |
| lib.rs | token_trie |
| version | 0.1.0 |
| created_at | 2025-09-22 08:28:01.395271+00 |
| updated_at | 2025-09-22 08:28:01.395271+00 |
| description | A high-performance Radix Trie implementation with sorted children for efficient binary search operations |
| homepage | https://github.com/reyoung/token_trie |
| repository | https://github.com/reyoung/token_trie |
| max_upload_size | |
| id | 1849663 |
| size | 68,883 |
A high-performance Radix Trie implementation in Rust with sorted children for efficient binary search operations.
Clone + Ord + PartialEqAdd this to your Cargo.toml:
[dependencies]
token_trie = "0.1.0"
use token_trie::Trie;
// Create a new trie
let mut trie = Trie::new();
// Insert key-value pairs
trie.insert(&['h', 'e', 'l', 'l', 'o'], "greeting");
trie.insert(&['h', 'e', 'l', 'p'], "assistance");
trie.insert(&['w', 'o', 'r', 'l', 'd'], "earth");
// Look up values
assert_eq!(trie.get(&['h', 'e', 'l', 'l', 'o']), Some(&"greeting"));
assert_eq!(trie.get(&['f', 'o', 'o']), None);
// Prefix search
let he_words = trie.keys_with_prefix(&['h', 'e']);
println!("Words starting with 'he': {:?}", he_words);
// Common prefix length
let prefix_len = trie.common_prefix_length(&['h', 'e', 'l', 'p', 'e', 'r']);
assert_eq!(prefix_len, 4); // Matches "help"
The trie works excellently with integer sequences, making it perfect for token-based applications:
use token_trie::Trie;
let mut token_trie = Trie::new();
// Insert token sequences
token_trie.insert(&[1, 2, 3], "sequence_a");
token_trie.insert(&[1, 2, 4], "sequence_b");
token_trie.insert(&[1, 5], "sequence_c");
// Find all sequences starting with [1, 2]
let sequences = token_trie.keys_with_prefix(&[1, 2]);
// Returns: [[1, 2, 3], [1, 2, 4]]
new() - Create a new empty trieinsert(&[Key], Value) - Insert a key-value pairget(&[Key]) -> Option<&Value> - Get value for a keyremove(&[Key]) -> Option<Value> - Remove and return value for a keycontains_key(&[Key]) -> bool - Check if key existskeys_with_prefix(&[Key]) -> Vec<Vec<Key>> - Get all keys with given prefixcommon_prefix_length(&[Key]) -> usize - Find longest common prefix lengthiter() -> Vec<(Vec<Key>, &Value)> - Get all key-value pairskeys() -> Vec<Vec<Key>> - Get all keyslen() -> usize - Number of key-value pairsis_empty() -> bool - Check if trie is emptyThis implementation uses a Radix Trie (compressed trie) with the following optimizations:
Run the comprehensive demo:
cargo run --example demo
The implementation includes extensive test coverage:
cargo test
Test categories:
MIT License - see LICENSE file for details.
Contributions are welcome! Please ensure all tests pass and add tests for new features.