Oops.
[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 "array.h"
37 #include "str.h"
38 #include "trie.h"
39
40 typedef struct trie_entry_t trie_entry_t;
41
42 struct trie_entry_t {
43     uint32_t c_offset;
44     uint32_t children_offset;
45
46     uint16_t c_len;
47     uint16_t children_len;
48 };
49 #define TRIE_ENTRY_INIT { 0, 0, 0, 0 }
50 ARRAY(trie_entry_t)
51
52 struct trie_t {
53     A(trie_entry_t) entries;
54     A(char)         c;
55     A(char)         keys;
56     A(int)          keys_offset;
57
58     bool locked;
59 };
60
61 trie_t *trie_new(void)
62 {
63     return p_new(trie_t, 1);
64 }
65
66 static inline void trie_cleanup_build_data(trie_t *trie)
67 {
68     array_wipe(trie->keys);
69     array_wipe(trie->keys_offset);
70 }
71
72 void trie_delete(trie_t **trie)
73 {
74     if (*trie) {
75         trie_cleanup_build_data(*trie);
76         trie_unlock(*trie);
77         array_wipe((*trie)->entries);
78         array_wipe((*trie)->c);
79         p_delete(trie);
80     }
81 }
82
83 /** Check that the given entry is a prefix for the given key.
84  */
85 static inline bool trie_entry_c_match(const trie_t *trie,
86                                       const trie_entry_t *entry,
87                                       const char *key, int *pos)
88 {
89     const char *c = array_ptr(trie->c, entry->c_offset);
90     int i = 0;
91     for (i = 0 ; i < entry->c_len ; ++i) {
92         if (key[i] != c[i]) {
93             if (pos) {
94                 *pos = i;
95             }
96             return false;
97         }
98     }
99     if (pos) {
100         *pos = i;
101     }
102     return true;
103 }
104
105 static inline bool trie_entry_match(const trie_t *trie,
106                                     const trie_entry_t *entry, const char *key)
107 {
108     return !!(strcmp(array_ptr(trie->c, entry->c_offset), key) == 0);
109 }
110
111 static inline bool trie_entry_prefix(const trie_t *trie,
112                                      const trie_entry_t *entry, const char *key)
113 {
114     int len = entry->c_len;
115     if (len > 0 && array_elt(trie->c, entry->c_offset + len - 1) == '\0') {
116         --len;
117     }
118     return !!(strncmp(array_ptr(trie->c, entry->c_offset), key, len) == 0);
119 }
120
121 static inline bool trie_entry_is_leaf(const trie_entry_t *entry)
122 {
123     return entry->children_len == 0;
124 }
125
126 /** Lookup for a child of entry matching the given entry at the given pos.
127  * Only the first character of the children is taken into account in the
128  * lookup. The current entry is assumed to match the key.
129  */
130 static inline trie_entry_t* trie_entry_child(const trie_t *trie,
131                                              const trie_entry_t* entry,
132                                              const char *key)
133 {
134     int start = entry->children_offset;
135     int end   = start + entry->children_len;
136     const char c = *key;
137
138     while (start < end) {
139         int mid = (start + end) / 2;
140         trie_entry_t* child = array_ptr(trie->entries, mid);
141         const char c2 = array_elt(trie->c, child->c_offset);
142
143         if (child->c_len) {
144             if (c2 == c) {
145                 return child;
146             }
147             if (c < c2) {
148                 end = mid;
149             } else {
150                 start = mid + 1;
151             }
152         } else {
153             abort();
154         }
155     }
156     return NULL;
157 }
158
159 static inline uint32_t trie_entry_new(trie_t *trie)
160 {
161     const trie_entry_t e = TRIE_ENTRY_INIT;
162     array_add(trie->entries, e);
163     return trie->entries.len - 1;
164 }
165
166 static inline uint32_t trie_add_leaf(trie_t *trie, const char *key)
167 {
168     trie_entry_t *entry;
169     int len = m_strlen(key) + 1;
170     entry = array_ptr(trie->entries, trie_entry_new(trie));
171     entry->c_offset = trie->c.len;
172     entry->c_len    = len;
173     array_append(trie->c, key, len);
174     return trie->entries.len - 1;
175 }
176
177 static inline void trie_entry_insert_child(trie_t *trie, trie_entry_t *entry,
178                                            uint32_t pchild)
179 {
180     if (entry->children_len == 0) {
181         entry->children_offset = pchild;
182         entry->children_len    = 1;
183     } else {
184         if (entry->children_offset + entry->children_len != pchild) {
185             printf("Inserting child %d while offset is %d[%d]\n",
186                    pchild, entry->children_offset, entry->children_len);
187             abort();
188         }
189         ++entry->children_len;
190     }
191 }
192
193 static inline void trie_entry_split(trie_t *trie, trie_entry_t *entry, uint16_t pos)
194 {
195     trie_entry_t *child;
196     child    = array_ptr(trie->entries, trie_entry_new(trie));
197     if (pos == 0) {
198         child->c_offset = entry->c_offset;
199         child->c_len    = entry->c_len;
200         entry->c_offset = 0;
201         entry->c_len    = 0;
202     } else {
203         child->c_offset = entry->c_offset + pos;
204         child->c_len    = entry->c_len - pos;
205         entry->c_len    = pos;
206     }
207     child->children_offset = entry->children_offset;
208     child->children_len    = entry->children_len;
209     entry->children_offset = trie->entries.len - 1;
210     entry->children_len    = 1;
211 }
212
213 void trie_insert(trie_t *trie, const char* key)
214 {
215     assert(trie->entries.len == 0 && "Trie already compiled");
216
217     int len = m_strlen(key) + 1;
218     array_add(trie->keys_offset, trie->keys.len);
219     array_append(trie->keys, key, len);
220 }
221
222
223 static inline void trie_compile_aux(trie_t *trie, uint32_t id,
224                                     uint32_t first_key, uint32_t last_key,
225                                     int offset, int initial_diff)
226 {
227     uint32_t forks[256];
228     uint32_t fork_pos = 0;
229     char current = '\0';
230
231     for (int off_diff = initial_diff ; fork_pos == 0 ; ++off_diff, ++offset) {
232         current = array_elt(trie->keys, array_elt(trie->keys_offset, first_key) + offset);
233         for (uint32_t i = first_key + 1 ; i < last_key ; ++i) {
234             const char *str = array_ptr(trie->keys, array_elt(trie->keys_offset, i));
235             const char c = str[offset];
236             if (c != current) {
237                 array_ensure_capacity_delta(trie->entries, 2);
238                 if (fork_pos == 0) {
239                     trie_entry_split(trie, array_ptr(trie->entries, id), off_diff);
240                 }
241                 trie_entry_insert_child(trie, array_ptr(trie->entries, id),
242                                         trie_add_leaf(trie, str + offset));
243                 forks[fork_pos++] = i;
244                 current = c;
245             }
246         }
247         if (fork_pos == 0 && current == '\0') {
248             return;
249         }
250     }
251     forks[fork_pos] = last_key;
252
253     const uint8_t children_len = array_elt(trie->entries, id).children_len;
254     for (uint16_t i = 0 ; i < children_len ; ++i) {
255         int child = array_elt(trie->entries, id).children_offset + i;
256         if (forks[i] - 1 > first_key) {
257             trie_compile_aux(trie, child, first_key, forks[i], offset, 1);
258         }
259         first_key = forks[i];
260     }
261 }
262
263 void trie_compile(trie_t *trie, bool memlock)
264 {
265     assert(trie->entries.len == 0 && "Trie already compiled");
266     assert(trie->keys.len != 0 && "Trying to compile an empty trie");
267     {
268 #       define QSORT_TYPE int
269 #       define QSORT_BASE trie->keys_offset.data
270 #       define QSORT_NELT trie->keys_offset.len
271 #       define QSORT_LT(a,b) strcmp(trie->keys.data + *a, trie->keys.data + *b) < 0
272 #       include "qsort.c"
273     }
274
275     array_ensure_capacity(trie->entries, trie->keys.len);
276     trie_compile_aux(trie, trie_add_leaf(trie, trie->keys.data),
277                      0, trie->keys_offset.len, 0, 0);
278     trie_cleanup_build_data(trie);
279     array_adjust(trie->entries);
280     array_adjust(trie->c);
281     if (memlock) {
282         trie_lock(trie);
283     }
284 }
285
286 bool trie_lookup(const trie_t *trie, const char *key)
287 {
288     assert(trie->keys.len == 0L && "Can't lookup: trie not compiled");
289     if (trie->entries.len == 0) {
290         return false;
291     } else {
292         trie_entry_t *current = array_ptr(trie->entries, 0);
293         while (true) {
294             int pos = 0;
295             if (trie_entry_is_leaf(current)) {
296                 return trie_entry_match(trie, current, key);
297             } else if (trie_entry_c_match(trie, current, key, &pos)) {
298                 key += pos;
299                 current = trie_entry_child(trie, current, key);
300                 if (current == NULL) {
301                     return false;
302                 }
303             } else {
304                 return false;
305             }
306         }
307     }
308 }
309
310 bool trie_prefix(const trie_t *trie, const char *key)
311 {
312     assert(trie->keys.len == 0L && "Can't lookup: trie not compiled");
313     if (trie->entries.len == 0) {
314         return false;
315     } else {
316         trie_entry_t *current = array_ptr(trie->entries, 0);
317         while (true) {
318             int pos = 0;
319             if (trie_entry_is_leaf(current)) {
320                 return trie_entry_prefix(trie, current, key);
321             } else if (trie_entry_c_match(trie, current, key, &pos)) {
322                 key += pos;
323                 current = trie_entry_child(trie, current, key);
324                 if (current == NULL) {
325                     return false;
326                 }
327             } else {
328                 return false;
329             }
330         }
331     }
332 }
333
334 void trie_lock(trie_t *trie)
335 {
336     if (trie->locked) {
337         return;
338     }
339     if (!array_lock(trie->entries)) {
340         UNIXERR("mlock");
341     }
342     if (!array_lock(trie->c)) {
343         UNIXERR("mlock");
344     }
345     if (mlock(trie, sizeof(trie_t)) != 0) {
346         UNIXERR("mlock");
347         return;
348     }
349     trie->locked = true;
350 }
351
352 void trie_unlock(trie_t *trie)
353 {
354     if (!trie->locked) {
355         return;
356     }
357     array_unlock(trie->entries);
358     array_unlock(trie->c);
359     munlock(trie, sizeof(trie_t));
360     trie->locked = false;
361 }
362
363 /* Debug {{{1
364  */
365
366 static inline void trie_entry_inspect(const trie_t *trie, bool show_content,
367                                       const trie_entry_t *entry, int level)
368 {
369     static int max_depth = 0;
370     static int leaves    = 0;
371     static int depth_sum = 0;
372
373     if (entry == array_ptr(trie->entries, 0)) {
374       max_depth = 0;
375       leaves    = 0;
376       depth_sum = 0;
377     }
378     if (trie_entry_is_leaf(entry)) {
379         if (level > max_depth) {
380             max_depth = level;
381         }
382         ++leaves;
383         depth_sum += level;
384     }
385     if (show_content) {
386         for (int i = 0 ; i < level ; ++i) {
387             fputs("  ", stdout);
388         }
389         if (entry->c_len == 0) {
390             fputs("(nil)", stdout);
391         } else {
392             const char *c = array_ptr(trie->c, entry->c_offset);
393             printf("(%d) ", entry->c_len);
394             for (int i = 0 ; i < entry->c_len ; ++i) {
395                 if (c[i]) {
396                     printf("%c ", c[i]);
397                 } else {
398                     fputs("\\0 ", stdout);
399                 }
400             }
401         }
402         fputs("\n", stdout);
403     }
404     for (uint32_t i = entry->children_offset ;
405           i < entry->children_offset + entry->children_len ; ++i) {
406         trie_entry_inspect(trie, show_content, array_ptr(trie->entries, i), level + 1);
407     }
408     if (level == 0) {
409         printf("Average char per node: %d\n", trie->c.len / trie->entries.len);
410         printf("Number of nodes: %d\n", trie->entries.len);
411         printf("Number of leaves: %d\n", leaves);
412         printf("Max depth: %d\n", max_depth);
413         printf("Average leaf depth: %d\n", depth_sum / leaves);
414         printf("Memory used: %d\n", (trie->entries.size * sizeof(trie_entry_t))
415                                   + (trie->c.size) + sizeof(trie_t));
416     }
417 }
418
419 void trie_inspect(const trie_t *trie, bool show_content)
420 {
421     trie_entry_inspect(trie, show_content, trie->entries.data, 0);
422 }