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