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