Add array framework that works with any type.
[apps/pfixtools.git] / common / trie.c
1 /******************************************************************************/
2 /*          pfixtools: a collection of postfix related tools                  */
3 /*          ~~~~~~~~~                                                         */
4 /*  ________________________________________________________________________  */
5 /*                                                                            */
6 /*  Redistribution and use in source and binary forms, with or without        */
7 /*  modification, are permitted provided that the following conditions        */
8 /*  are met:                                                                  */
9 /*                                                                            */
10 /*  1. Redistributions of source code must retain the above copyright         */
11 /*     notice, this list of conditions and the following disclaimer.          */
12 /*  2. Redistributions in binary form must reproduce the above copyright      */
13 /*     notice, this list of conditions and the following disclaimer in the    */
14 /*     documentation and/or other materials provided with the distribution.   */
15 /*  3. The names of its contributors may not be used to endorse or promote    */
16 /*     products derived from this software without specific prior written     */
17 /*     permission.                                                            */
18 /*                                                                            */
19 /*  THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND   */
20 /*  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE     */
21 /*  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR        */
22 /*  PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS    */
23 /*  BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR    */
24 /*  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF      */
25 /*  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS  */
26 /*  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN   */
27 /*  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)   */
28 /*  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF    */
29 /*  THE POSSIBILITY OF SUCH DAMAGE.                                           */
30 /******************************************************************************/
31
32 /*
33  * Copyright © 2008 Florent Bruneau
34  */
35
36 #include <sys/mman.h>
37
38 #include "array.h"
39 #include "str.h"
40 #include "trie.h"
41
42 typedef struct trie_entry_t trie_entry_t;
43
44 struct trie_entry_t {
45     int32_t  c_offset;
46     int32_t  c_len;
47
48     int32_t children_offset;
49     int32_t children_len;
50 };
51 #define TRIE_ENTRY_INIT { 0, 0, 0, 0 }
52 ARRAY(trie_entry_t)
53
54 struct trie_t {
55     trie_entry_t_array_t entries;
56     char_array_t         c;
57     char_array_t         keys;
58     int_array_t          keys_offset;
59
60     bool locked;
61 };
62
63 trie_t *trie_new(void)
64 {
65     return p_new(trie_t, 1);
66 }
67
68 static inline void trie_cleanup_build_data(trie_t *trie)
69 {
70     array_wipe(trie->keys);
71     array_wipe(trie->keys_offset);
72 }
73
74 void trie_delete(trie_t **trie)
75 {
76     if (*trie) {
77         trie_cleanup_build_data(*trie);
78         trie_unlock(*trie);
79         array_wipe((*trie)->entries);
80         array_wipe((*trie)->c);
81         p_delete(trie);
82     }
83 }
84
85 /** Check that the given entry is a prefix for the given key.
86  */
87 static inline bool trie_entry_c_match(const trie_t *trie,
88                                       const trie_entry_t *entry,
89                                       const char *key, int *pos)
90 {
91     const char *c = array_ptr(trie->c, entry->c_offset);
92     int i = 0;
93     for (i = 0 ; i < entry->c_len ; ++i) {
94         if (key[i] != c[i]) {
95             if (pos) {
96                 *pos = i;
97             }
98             return false;
99         }
100     }
101     if (pos) {
102         *pos = i;
103     }
104     return true;
105 }
106
107 static inline bool trie_entry_match(const trie_t *trie,
108                                     const trie_entry_t *entry, const char *key)
109 {
110     return !!(strcmp(array_ptr(trie->c, entry->c_offset), key) == 0);
111 }
112
113 static inline bool trie_entry_is_leaf(const trie_entry_t *entry)
114 {
115     return entry->children_len == 0;
116 }
117
118 /** Lookup for a child of entry matching the given entry at the given pos.
119  * Only the first character of the children is taken into account in the
120  * lookup. The current entry is assumed to match the key.
121  */
122 static inline trie_entry_t* trie_entry_child(const trie_t *trie,
123                                              const trie_entry_t* entry,
124                                              const char *key)
125 {
126     int start = entry->children_offset;
127     int end   = start + entry->children_len;
128     const char c = *key;
129
130     while (start < end) {
131         int mid = (start + end) / 2;
132         trie_entry_t* child = array_ptr(trie->entries, mid);
133         const char c2 = array_elt(trie->c, child->c_offset);
134
135         if (child->c_len) {
136             if (c2 == c) {
137                 return child;
138             }
139             if (c < c2) {
140                 end = mid;
141             } else {
142                 start = mid + 1;
143             }
144         } else {
145             abort();
146         }
147     }
148     return NULL;
149 }
150
151 static inline int trie_entry_new(trie_t *trie)
152 {
153     const trie_entry_t e = TRIE_ENTRY_INIT;
154     array_add(trie->entries, e);
155     return trie->entries.len;
156 }
157
158 static inline int trie_add_leaf(trie_t *trie, const char *key)
159 {
160     trie_entry_t *entry;
161     int len = m_strlen(key) + 1;
162     entry = array_ptr(trie->entries, trie_entry_new(trie));
163     entry->c_offset = trie->c.len;
164     entry->c_len    = len;
165     array_append(trie->c, key, len);
166     return trie->entries.len - 1;
167 }
168
169 static inline void trie_entry_insert_child(trie_t *trie, trie_entry_t *entry,
170                                            int pchild)
171 {
172     if (entry->children_len == 0) {
173         entry->children_offset = pchild;
174         entry->children_len    = 1;
175     } else {
176         if (entry->children_offset + entry->children_len != pchild) {
177             printf("Inserting child %d while offset is %d[%d]\n",
178                    pchild, entry->children_offset, entry->children_len);
179             abort();
180         }
181         ++entry->children_len;
182     }
183 }
184
185 static inline void trie_entry_split(trie_t *trie, trie_entry_t *entry, int pos)
186 {
187     trie_entry_t *child;
188     child    = array_ptr(trie->entries, trie_entry_new(trie));
189     if (pos == 0) {
190         child->c_offset = entry->c_offset;
191         child->c_len    = entry->c_len;
192         entry->c_offset = 0;
193         entry->c_len    = 0;
194     } else {
195         child->c_offset = entry->c_offset + pos;
196         child->c_len    = entry->c_len - pos;
197         entry->c_len    = pos;
198     }
199     child->children_offset = entry->children_offset;
200     child->children_len    = entry->children_len;
201     entry->children_offset = trie->entries.len - 1;
202     entry->children_len    = 1;
203 }
204
205 void trie_insert(trie_t *trie, const char* key)
206 {
207     assert(trie->entries.len == 0 && "Trie already compiled");
208
209     int len = m_strlen(key) + 1;
210     array_add(trie->keys_offset, trie->keys.len);
211     array_append(trie->keys, key, len);
212 }
213
214
215 static inline void trie_compile_aux(trie_t *trie, int id,
216                                     int first_key, int last_key, int offset,
217                                     int initial_diff)
218 {
219     int forks[256];
220     int fork_pos = 0;
221     char current = '\0';
222
223     for (int off_diff = initial_diff ; fork_pos == 0 ; ++off_diff, ++offset) {
224         current = array_elt(trie->keys, array_elt(trie->keys_offset, first_key) + offset);
225         for (int i = first_key + 1 ; i < last_key ; ++i) {
226             const char *str = array_ptr(trie->keys, array_elt(trie->keys_offset, i));
227             const char c = str[offset];
228             if (c != current) {
229                 array_ensure_capacity_delta(trie->entries, 2);
230                 if (fork_pos == 0) {
231                     trie_entry_split(trie, array_ptr(trie->entries, id), off_diff);
232                 }
233                 trie_entry_insert_child(trie, array_ptr(trie->entries, id),
234                                         trie_add_leaf(trie, str + offset));
235                 forks[fork_pos++] = i;
236                 current = c;
237             }
238         }
239         if (fork_pos == 0 && current == '\0') {
240             return;
241         }
242     }
243     forks[fork_pos] = last_key;
244
245     const int children_len = array_elt(trie->entries, id).children_len;
246     for (int i = 0 ; i < children_len ; ++i) {
247         int child = array_elt(trie->entries, id).children_offset + i;
248         if (forks[i] - 1 > first_key) {
249             trie_compile_aux(trie, child, first_key, forks[i], offset, 1);
250         }
251         first_key = forks[i];
252     }
253 }
254
255 void trie_compile(trie_t *trie, bool memlock)
256 {
257     assert(trie->entries.len == 0 && "Trie already compiled");
258     assert(trie->keys.len != 0 && "Trying to compile an empty trie");
259     {
260 #       define QSORT_TYPE int
261 #       define QSORT_BASE trie->keys_offset.data
262 #       define QSORT_NELT trie->keys_offset.len
263 #       define QSORT_LT(a,b) strcmp(trie->keys.data + *a, trie->keys.data + *b) < 0
264 #       include "qsort.c"
265     }
266
267     array_ensure_capacity(trie->entries, trie->keys.len);
268     trie_compile_aux(trie, trie_add_leaf(trie, trie->keys.data),
269                      0, trie->keys_offset.len, 0, 0);
270     trie_cleanup_build_data(trie);
271     array_adjust(trie->entries);
272     array_adjust(trie->c);
273     if (memlock) {
274         trie_lock(trie);
275     }
276 }
277
278 bool trie_lookup(const trie_t *trie, const char *key)
279 {
280     assert(trie->keys.len == 0L && "Can't lookup: trie not compiled");
281     if (trie->entries.len == 0) {
282         return false;
283     } else {
284         trie_entry_t *current = array_ptr(trie->entries, 0);
285         while (true) {
286             int pos = 0;
287             if (trie_entry_is_leaf(current)) {
288                 return trie_entry_match(trie, current, key);
289             } else if (trie_entry_c_match(trie, current, key, &pos)) {
290                 key += pos;
291                 current = trie_entry_child(trie, current, key);
292                 if (current == NULL) {
293                     return false;
294                 }
295             } else {
296                 return false;
297             }
298         }
299     }
300 }
301
302 void trie_lock(trie_t *trie)
303 {
304     if (trie->locked) {
305         return;
306     }
307     if (mlock(trie->entries.data, sizeof(trie_entry_t) * trie->entries.len) != 0) {
308         UNIXERR("mlock");
309         return;
310     }
311     if (mlock(trie->c.data, trie->c.len) != 0) {
312         UNIXERR("mlock");
313         munlock(trie->entries.data, sizeof(trie_entry_t) * trie->entries.len);
314         return;
315     }
316     trie->locked = true;
317 }
318
319 void trie_unlock(trie_t *trie)
320 {
321     if (!trie->locked) {
322         return;
323     }
324     munlock(trie->entries.data, sizeof(trie_entry_t) * trie->entries.len);
325     munlock(trie->c.data, trie->c.len);
326     trie->locked = false;
327 }
328
329 /* Debug {{{1
330  */
331
332 static inline void trie_entry_inspect(const trie_t *trie, bool show_content,
333                                       const trie_entry_t *entry, int level)
334 {
335     static int max_depth = 0;
336     static int leaves    = 0;
337     static int depth_sum = 0;
338
339     if (trie_entry_is_leaf(entry)) {
340         if (level > max_depth) {
341             max_depth = level;
342         }
343         ++leaves;
344         depth_sum += level;
345     }
346     if (show_content) {
347         for (int i = 0 ; i < level ; ++i) {
348             fputs("  ", stdout);
349         }
350         if (entry->c_len == 0) {
351             fputs("(nil)", stdout);
352         } else {
353             const char *c = array_ptr(trie->c, entry->c_offset);
354             printf("(%d) ", entry->c_len);
355             for (int i = 0 ; i < entry->c_len ; ++i) {
356                 if (c[i]) {
357                     printf("%c ", c[i]);
358                 } else {
359                     fputs("\\0 ", stdout);
360                 }
361             }
362         }
363         fputs("\n", stdout);
364     }
365     for (int i = entry->children_offset ;
366           i < entry->children_offset + entry->children_len ; ++i) {
367         trie_entry_inspect(trie, show_content, array_ptr(trie->entries, i), level + 1);
368     }
369     if (level == 0) {
370         printf("Average char per node: %d\n", trie->c.len / trie->entries.len);
371         printf("Number of nodes: %d\n", trie->entries.len);
372         printf("Number of leaves: %d\n", leaves);
373         printf("Max depth: %d\n", max_depth);
374         printf("Average leaf depth: %d\n", depth_sum / leaves);
375         printf("Memory used: %d\n", (trie->entries.size * sizeof(trie_entry_t))
376                                   + (trie->c.size) + sizeof(trie_t));
377     }
378 }
379
380 void trie_inspect(const trie_t *trie, bool show_content)
381 {
382     trie_entry_inspect(trie, show_content, trie->entries.data, 0);
383 }