1 // Copyright © Tavian Barnes <tavianator@tavianator.com>
2 // SPDX-License-Identifier: 0BSD
17 /** Linked list of leaves, in insertion order. */
18 struct trie_leaf *prev, *next;
19 /** An arbitrary value associated with this leaf. */
21 /** The length of the key in bytes. */
23 /** The key itself, stored inline. */
28 * A trie that holds a set of fixed- or variable-length strings.
31 /** Pointer to the root node/leaf. */
33 /** Linked list of leaves. */
34 struct trie_leaf *head, *tail;
35 /** Node allocator. */
37 /** Leaf allocator. */
42 * Initialize an empty trie.
44 void trie_init(struct trie *trie);
47 * Find the leaf for a string key.
54 * The found leaf, or NULL if the key is not present.
56 struct trie_leaf *trie_find_str(const struct trie *trie, const char *key);
59 * Find the leaf for a fixed-size key.
66 * The length of the key in bytes.
68 * The found leaf, or NULL if the key is not present.
70 struct trie_leaf *trie_find_mem(const struct trie *trie, const void *key, size_t length);
73 * Find the shortest leaf that starts with a given key.
80 * A leaf that starts with the given key, or NULL.
82 struct trie_leaf *trie_find_postfix(const struct trie *trie, const char *key);
85 * Find the leaf that is the longest prefix of the given key.
92 * The longest prefix match for the given key, or NULL.
94 struct trie_leaf *trie_find_prefix(const struct trie *trie, const char *key);
97 * Insert a string key into the trie.
100 * The trie to modify.
104 * The inserted leaf, or NULL on failure.
106 struct trie_leaf *trie_insert_str(struct trie *trie, const char *key);
109 * Insert a fixed-size key into the trie.
112 * The trie to modify.
116 * The length of the key in bytes.
118 * The inserted leaf, or NULL on failure.
120 struct trie_leaf *trie_insert_mem(struct trie *trie, const void *key, size_t length);
123 * Remove a leaf from a trie.
126 * The trie to modify.
128 * The leaf to remove.
130 void trie_remove(struct trie *trie, struct trie_leaf *leaf);
133 * Remove all leaves from a trie.
135 void trie_clear(struct trie *trie);
138 * Destroy a trie and its contents.
140 void trie_destroy(struct trie *trie);
143 * Iterate over the leaves of a trie.
145 #define for_trie(leaf, trie) \
146 for_list(struct trie_leaf, leaf, trie)