A compressed radix trie (a.k.a. PATRICIA trie / radix tree) for storing and querying strings, with exact-match and prefix search. Written in pure, zero-dependency Rust.
A naive trie stores one node per character. That is simple to implement, but wasteful in memory and pointer-chasing whenever your word set contains long unbranching runs of characters — which is the common case for anything resembling real words (dictionaries, URL paths, DNS labels, autocomplete corpora, routing tables). A compressed radix trie instead stores one edge per shared substring: any chain of nodes that each have exactly one child gets collapsed into a single edge labeled with the whole run of characters. The number of internal nodes then tracks the number of actual branching points in your word set, not the total character count.
This crate is a genuine implementation of that structure — including the
edge-splitting logic required to keep the compression correct as new words
are inserted — not a toy trie with an inaccurate name. It is intentionally
scoped to what a "real, useful primitive" needs: insertion and exact/prefix
lookup. It does not implement deletion, does not support non-UTF-8 byte
strings, and does not attempt fancy allocation tricks (e.g. arenas, interned
labels) — the node/edge design uses ordinary owned Strings and Boxes,
which is simple and correct but not maximally cache-friendly. If you need
deletion or byte-string keys, this is a reasonable base to extend rather
than a drop-in for those needs.
use rs_trie::Trie;
fn main() {
let mut trie = Trie::new();
for word in ["car", "card", "care", "careful", "cat"] {
trie.insert(word);
}
// Exact match: "car" is itself a stored word, even though "card" and
// "care" both extend it.
assert!(trie.contains("car"));
assert!(trie.contains("careful"));
// "ca" was never inserted, so it is not an exact match...
assert!(!trie.contains("ca"));
// ...but it is a real prefix of stored words.
assert!(trie.starts_with("ca"));
// Collect every stored word with a given prefix.
let mut words = trie.find_by_prefix("car");
words.sort();
assert_eq!(words, vec!["car", "card", "care", "careful"]);
}Each node holds a list of outgoing edges. Every edge is labeled with a
non-empty string (not a single character) and points to the child node
it leads to. A node also carries an is_end flag, because a word can end
exactly at a node that also has children — for example, after inserting
both "car" and "card", the node reached by following the edge "car"
must have is_end = true (because "car" is itself a stored word) and a
child edge labeled "d" leading to the node for "card".
Inserting a word walks down from the root, consuming the word one edge at a
time. At each node, it looks for a child edge whose label shares a common
prefix (computed on char boundaries, so multi-byte UTF-8 is handled
correctly) with the remaining unconsumed suffix of the word. Three things
can happen:
-
No edge shares a prefix. A brand new edge is created, labeled with the entire remaining suffix, pointing straight to a new end-of-word leaf. This is the base case that lets the very first word (or a word unrelated to anything already stored) be inserted in one step.
-
An edge's whole label is a prefix of the remaining suffix. The existing edge is simply followed, and insertion continues recursively into its target node with whatever of the word is left.
-
An edge only partially overlaps the remaining suffix. This is the interesting case: the edge is split. A new intermediate node is created at the point where the two strings diverge. The original edge is shortened to just the shared prefix and now points at this new intermediate node; the rest of the original edge's label becomes a new edge from the intermediate node down to the original (unmodified) subtree; and the rest of the word being inserted becomes another new edge from the intermediate node down to a fresh leaf.
For example, inserting
"card"then"care": after the first insert, the root has one edge"card"to a leaf. Inserting"care"finds that edge's label"card"shares only the prefix"car"with"care". The edge is split: root --"car"--> (intermediate,is_end = false), which then has two children: --"d"--> leaf ("card") and --"e"--> leaf ("care"). No node here ever stored a single stray character on its own — the compression is exact from the moment a branch appears.
Because the split happens at the true point of divergence, and edges only grow (via appending a fresh child) or shrink-and-branch (via a split), the trie never degenerates into a per-character chain: a long run of characters shared by many words is walked and stored as a single edge for as long as no other inserted word diverges partway through it.
contains and starts_with both walk edges the same way insertion does:
at each node, find the (at most one, by construction) child edge that
shares a prefix with the remaining search string, and either fully consume
the edge and recurse, or fail immediately if the search string diverges
partway through an edge label. contains additionally requires that the
final node's is_end flag be set — a word that is merely a prefix of
something stored (like "ca" when only "car" is stored) must not count
as contained. find_by_prefix walks down to the node (or point within an
edge) where the requested prefix is fully consumed, then does a full
subtree traversal from there, reconstructing every complete word from the
edge labels walked along the way.
cargo testThe test suite specifically exercises:
- Prefix-vs-word correctness:
"car"and"card"are both stored and both independently reachable viacontains, while"ca"(never inserted) correctly reportscontains() == falseandstarts_with() == true. - Edge splitting under long shared prefixes: words like
"international","internationalize", and"internationalization"are inserted together to force multiple rounds of edge splitting, then every one of them (and only them) is verified reachable. - Exact
find_by_prefixresult sets, compared against a known sorted list of expected words, not just "non-empty". - A concrete compression proof: 50 words sharing a 25-character common
prefix (1,350 total characters across all words) are inserted, and the
test asserts, via an exposed
Trie::node_count(), that the tree uses far fewer internal nodes than the character count would suggest for a naive trie — and directly checks, by inspecting the root's single child edge, that the entire 25-character shared prefix was stored as one edge rather than 25 separate one-character nodes. - Unicode words with multi-byte characters, to confirm edge splitting never
panics by slicing a
Stringoff a UTF-8 character boundary.
MIT. See LICENSE.