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