7 * Double Array Trie algorithm, based on:
8 * An Efficient Implementation of Trie Structures, by
9 * Jun-ichi Aoe and Katsushi Maromoto, and Takashi Sato
10 * from Sofiware - Practice and Experience, Vol. 22(9), 695-721 (September 1992)
12 * A Trie is a simple data structure which stores strings as DFAs, with each
13 * transition state being a string entry. For example, observe the following strings:
15 * BAILOPAN, BAT, BACON, BACK
16 * These transition as the follow production rules:
27 * The standard implementation for this - using lists - gives a slow linear lookup, somewhere between
28 * O(N+M) or O(log n). A faster implementation is proposed in the paper above, which is based on compacting
29 * the transition states into two arrays. In the paper's implementation, two arrays are used, and thus it is
30 * called the "Double Array" algorithm. However, the CHECK array's size is maintained the same as BASE,
31 * so they can be combined into one structure. The array seems complex at first, but is very simple: it is a
32 * tree structure flattened out into a single vector. I am calling this implementation the Flat Array Trie.
34 * BASE[] is an array where each member is a node in the Trie. The node can either be UNUSED (empty), an ARC
35 * (containing an offset to the next set of ARCs), or a TERMINATOR (contains the rest of a string).
36 * Each node has an index which must be interpeted based on the node type. If the node is a TERMINATOR, then the
37 * index is an index into a string table, to find the rest of the string.
38 * If the node is an ARC, the index is another index into BASE. For each possible token that can follow the
39 * current token, the value of those tokens can be added to the index given in the ARC. Thus, given a current
40 * position and the next desired token, the current arc will jump to another arc which can contain either:
41 * 1) An invalid production (collision, no entry exists)
42 * 2) An empty production (no entry exists)
43 * 3) Another arc label (the string ends here or continues into more productions)
44 * 4) A TERMINATOR (the string ends here and contains an unused set of productions)
46 * So, given current offset N (starting at N=1), jumping to token C means the next offset will be:
48 * Thus, the next node will be at:
51 * This allows each ARC to specify the base offset for any of its ARC children, like a tree. Each node specifies
52 * its parent ARC -- so if an invalid offset is specified, the parent will not match, and thus no such derived
55 * This means that arrays can be laid out "sparsely," maximizing their usage. Note that N need not be related to
56 * the range of tokens (1-256). I.e., a base index does not have to be at 1, 256, 512, et cetera. This is because
57 * insertion comes with a small deal of complexity. To insert a new set of tokens T, the algorithm finds a new
58 * BASE index N such that BASE[N+T[i]] is unused for each T[i]. Thus, indirection is not necessarily linear;
59 * traversing a chain of ARC nodes can _and will_ jump around BASE.
61 * Of course, given this level of flexibility in the array organization, there are collisions. This is largely
62 * where insertions become slow, as the old chain must be relocated before the new one is used. Relocation means
63 * finding one or more new base indexes, and this means traversing BASE until an acceptable index is found, such
64 * that each offset is unused (see description in previous paragraph).
66 * However, it is not insertion time we are concerned about. The "trie" name comes from reTRIEval. We are only
67 * concerned with lookup and deletion. Both lookup and deletion are O(k), where k is relative to the length of the
68 * input string. Note that it is best case O(1) and worst case O(k). Deleting the entire trie is always O(1).
72 * Optimization ideas for the future:
73 * 1) Store a reference count for each arc, with the count of sub-children.
74 * This could let us break out of "children searches" for case 4 easily.
75 * 2) Use a 'free list' so we can easily search the trie for free points.
76 * This would drastically speed up x_check*
81 Node_Unused = 0, /* Node is not being used (sparse) */
82 Node_Arc, /* Node is part of an arc and does not terminate */
83 Node_Term, /* Node is a terminator */
89 * For Node_Arc, this index stores the 'base' offset to the next arc chain.
90 * I.e. to jump from this arc to character C, it will be at base[idx+C].
91 * For Node_Term, this is an index into the string table.
96 * This contains the prior arc that we must have come from.
97 * For example, if arc 63 has a base jump of index 12, and we want to see if
98 * there is a valid character C, the parent of 12+C must be 63.
102 void *value; /* Value associated with this node */
103 NodeType mode; /* Current usage type of the node */
104 bool valset; /* Whether or not a value is set */
109 TrieNode *base; /* Base array for the sparse tables */
110 char *stringtab; /* String table pointer */
111 unsigned int baseSize; /* Size of the base array, in members */
112 unsigned int stSize; /* Size of the string table, in bytes */
113 unsigned int tail; /* Current unused offset into the string table */
116 inline unsigned char charval(char c)
118 return (unsigned char)c;
121 bool sm_trie_grow(Trie *trie)
123 /* The current # of nodes in the tree is trie->baseSize + 1 */
124 unsigned int curSize = trie->baseSize;
125 unsigned int newSize = curSize * 2;
127 //:TODO: Make functions calling this return failure if this fails
128 trie->base = (TrieNode *)realloc(trie->base, (newSize + 1) * sizeof(TrieNode));
134 memset(&trie->base[curSize+1], 0, (newSize - curSize) * sizeof(TrieNode));
135 trie->baseSize = newSize;
140 unsigned int x_check(Trie *trie, char c, unsigned int start=1)
142 TrieNode *base = trie->base;
143 unsigned char _c = charval(c);
144 unsigned int to_check = trie->baseSize - _c;
145 for (unsigned int i=start; i<=to_check; i++)
147 if (base[i+_c].mode == Node_Unused)
155 return x_check(trie, c, to_check+1);
158 unsigned int x_check2(Trie *trie, char c1, char c2, unsigned int start=1)
160 TrieNode *base = trie->base;
161 unsigned char _c1 = charval(c1);
162 unsigned char _c2 = charval(c2);
163 unsigned int to_check = trie->baseSize - (_c1 > _c2 ? _c1 : _c2);
164 for (unsigned int i=start; i<=to_check; i++)
166 if (base[i+_c1].mode == Node_Unused
167 && base[i+_c2].mode == Node_Unused)
175 return x_check2(trie, c1, c2, to_check+1);
178 unsigned int x_check_multi(Trie *trie,
179 unsigned int offsets[],
181 unsigned int start=1)
183 TrieNode *base = trie->base;
185 unsigned int to_check = trie->baseSize;
186 unsigned int highest = 0;
188 for (unsigned int i=0; i<count; i++)
190 if (offsets[i] > highest)
192 highest = offsets[i];
198 for (unsigned int i=start; i<=to_check; i++)
201 for (unsigned int j=0; j<count; j++)
203 cur = &base[i+offsets[j]];
204 if (cur->mode != Node_Unused)
218 return x_check_multi(trie, offsets, count, to_check+1);
221 unsigned int x_addstring(Trie *trie, const char *ptr)
223 size_t len = strlen(ptr) + 1;
225 if (trie->tail + len >= trie->stSize)
227 while (trie->tail + len >= trie->stSize)
231 trie->stringtab = (char *)realloc(trie->stringtab, trie->stSize);
234 unsigned int tail = trie->tail;
235 strcpy(&trie->stringtab[tail], ptr);
241 Trie *sm_trie_create()
245 t->base = (TrieNode *)malloc(sizeof(TrieNode) * (256 + 1));
246 t->stringtab = (char *)malloc(sizeof(char) * 256);
251 memset(t->base, 0, sizeof(TrieNode) * (256 + 1));
252 memset(t->stringtab, 0, sizeof(char) * 256);
254 /* Sentinel root node */
256 t->base[1].mode = Node_Arc;
257 t->base[1].parent = 1;
262 void sm_trie_destroy(Trie *trie)
265 free(trie->stringtab);
269 bool sm_trie_delete(Trie *trie, const char *key)
271 unsigned int lastidx = 1; /* the last node index */
272 unsigned int curidx; /* current node index */
273 const char *keyptr = key; /* input stream at current token */
274 TrieNode *node = NULL; /* current node being processed */
275 TrieNode *base = trie->base;
282 /* Start traversing at the root node */
285 /* Find where the next character is, then advance */
286 curidx = base[lastidx].idx;
287 node = &base[curidx];
288 curidx += charval(*keyptr);
289 node = &base[curidx];
292 /* Check if this slot is supposed to be empty or is a collision */
293 if ((curidx > trie->baseSize) || node->mode == Node_Unused || node->parent != lastidx)
296 } else if (node->mode == Node_Term) {
297 char *term = &trie->stringtab[node->idx];
298 if (strcmp(keyptr, term) == 0)
304 } while (*keyptr != '\0');
306 assert(node != NULL);
313 node->valset = false;
319 bool sm_trie_retrieve(Trie *trie, const char *key, void **value)
321 unsigned int lastidx = 1; /* the last node index */
322 unsigned int curidx; /* current node index */
323 const char *keyptr = key; /* input stream at current token */
324 TrieNode *node = NULL; /* current node being processed */
325 TrieNode *base = trie->base;
332 /* Start traversing at the root node */
335 /* Find where the next character is, then advance */
336 curidx = base[lastidx].idx;
337 node = &base[curidx];
338 curidx += charval(*keyptr);
339 node = &base[curidx];
342 /* Check if this slot is supposed to be empty or is a collision */
343 if ((curidx > trie->baseSize) || node->mode == Node_Unused || node->parent != lastidx)
346 } else if (node->mode == Node_Term) {
347 char *term = &trie->stringtab[node->idx];
348 if (strcmp(keyptr, term) == 0)
354 } while (*keyptr != '\0');
356 assert(node != NULL);
365 *value = node->value;
371 bool sm_trie_insert(Trie *trie, const char *key, void *value)
373 unsigned int lastidx = 1; /* the last node index */
374 unsigned int curidx; /* current node index */
375 const char *keyptr = key; /* input stream at current token */
376 TrieNode *node = NULL; /* current node being processed */
377 TrieNode *basenode = NULL; /* current base node being processed */
378 unsigned int q; /* temporary var for x_check results */
379 TrieNode *base = trie->base;
380 unsigned int curoffs; /* current offset */
382 /* Do not handle empty strings for simplicity */
388 /* Start traversing at the root node (1) */
391 /* Find where the next character is, then advance */
392 curidx = base[lastidx].idx;
393 basenode = &base[curidx];
394 curoffs = charval(*keyptr);
396 node = &base[curidx];
399 /* Check if this slot is supposed to be empty. If so, we need to handle CASES 1/2:
400 * Insertion without collisions
402 if ( (curidx > trie->baseSize) || (node->mode == Node_Unused) )
404 if (curidx > trie->baseSize)
406 if (!sm_trie_grow(trie))
410 node = &trie->base[curidx];
412 node->parent = lastidx;
415 node->mode = Node_Arc;
417 node->idx = x_addstring(trie, keyptr);
418 node->mode = Node_Term;
424 } else if (node->parent != lastidx) {
425 /* Collision! We have to split up the tree here. CASE 4:
426 * Insertion when a new word is inserted with a collision.
427 * NOTE: This is the hardest case to handle. All below examples are based on:
428 * BACHELOR, BADGE, inserting BABY.
429 * The problematic production here is A -> B, where B is already being used.
431 * This process has to rotate one half of the 'A' arc. We generate two lists:
432 * Outgoing Arcs - Anything leaving this 'A'
433 * Incoming Arcs - Anything going to this 'A'
434 * Whichever list is smaller will be moved. Note that this works because the intersection
435 * affects both arc chains, and moving one will make the slot available to either.
439 /* Find every node arcing from the last node.
440 * I.e. for BACHELOR, BADGE, BABY,
441 * The arcs leaving A will be C and D, but our current node is B -> *.
442 * Thus, we use the last index (A) to find the base for arcs leaving A.
444 unsigned int outgoing_base = base[lastidx].idx;
445 unsigned int outgoing_list[256];
446 unsigned int outgoing_count = 0; /* count the current index here */
447 cur = &base[outgoing_base] + 1;
448 unsigned int outgoing_limit = 255;
450 if (outgoing_base + outgoing_limit > trie->baseSize)
452 outgoing_limit = trie->baseSize - outgoing_base;
455 for (unsigned int i=1; i<=outgoing_limit; i++,cur++)
457 if (cur->mode == Node_Unused || cur->parent != lastidx)
461 outgoing_list[outgoing_count++] = i;
463 outgoing_list[outgoing_count++] = curidx - outgoing_base;
465 /* Now we need to find all the arcs leaving our parent...
466 * Note: the inconsistency is the base of our parent.
468 assert(base[node->parent].mode == Node_Arc);
469 unsigned int incoming_list[256];
470 unsigned int incoming_base = base[node->parent].idx;
471 unsigned int incoming_count = 0;
472 unsigned int incoming_limit = 255;
473 cur = &base[incoming_base] + 1;
475 if (incoming_base + incoming_limit > trie->baseSize)
477 incoming_limit = trie->baseSize - incoming_base;
480 assert(incoming_limit > 0 && incoming_limit <= 255);
482 for (unsigned int i=1; i<=255; i++,cur++)
484 if (cur->mode == Node_Arc || cur->mode == Node_Term)
486 if (cur->parent == node->parent)
488 incoming_list[incoming_count++] = i;
493 if (incoming_count < outgoing_count + 1)
495 unsigned int q = x_check_multi(trie, incoming_list, incoming_count);
498 node = &base[curidx];
500 /* If we're incoming, we need to modify our parent */
501 base[node->parent].idx = q;
503 /* For each node in the "to move" list,
504 * Relocate the node's info to the new position.
506 unsigned int idx, newidx, oldidx;
507 for (unsigned int i=0; i<incoming_count; i++)
509 idx = incoming_list[i];
511 oldidx = incoming_base + idx;
512 if (oldidx == lastidx)
514 /* Important! Make sure we're not invalidating our sacred lastidx */
517 base[newidx] = base[oldidx];
518 assert(base[base[newidx].parent].mode == Node_Arc);
519 memset(&base[oldidx], 0, sizeof(TrieNode));
520 /* If we are not a terminator, we have children we must take care of */
521 if (base[newidx].mode == Node_Arc)
523 TrieNode *check_base = &base[base[newidx].idx] + 1;
524 for (unsigned int j=1; j<=255; j++, check_base++)
526 if (check_base->parent == oldidx)
528 check_base->parent = newidx;
534 unsigned int q = x_check_multi(trie, outgoing_list, outgoing_count);
537 node = &base[curidx];
539 /* If we're outgoing, we need to modify our own base */
540 base[lastidx].idx = q;
542 /* Take the last index (curidx) out of the list. Technically we are not moving this,
543 * since it's already being used by something else.
547 /* For each node in the "to move" list,
548 * Relocate the node's info to the new position.
550 unsigned int idx, newidx, oldidx;
551 for (unsigned int i=0; i<outgoing_count; i++)
553 idx = outgoing_list[i];
555 oldidx = outgoing_base + idx;
556 if (oldidx == lastidx)
558 /* Important! Make sure we're not invalidating our sacred lastidx */
561 base[newidx] = base[oldidx];
562 assert(base[base[newidx].parent].mode == Node_Arc);
563 memset(&base[oldidx], 0, sizeof(TrieNode));
564 /* If we are not a terminator, we have children we must take care of */
565 if (base[newidx].mode == Node_Arc)
567 TrieNode *check_base = &base[base[newidx].idx] + 1;
568 for (unsigned int j=1; j<=255; j++, check_base++)
570 if (check_base->parent == oldidx)
572 check_base->parent = newidx;
578 /* Take the invisible node and use it as our new node */
579 node = &base[q + outgoing_list[outgoing_count]];
582 /* We're finally done! */
583 node->parent = lastidx;
586 node->mode = Node_Arc;
588 node->idx = x_addstring(trie, keyptr);
589 node->mode = Node_Term;
596 /* See what's in the next node - special case if terminator! */
597 if (node->mode == Node_Term)
599 /* If we're a terminator, we need to handle CASE 3:
600 * Insertion when a terminating collision occurs
602 char *term = &trie->stringtab[node->idx];
603 /* Do an initial browsing to make sure they're not the same string */
604 if (strcmp(keyptr, term) == 0)
612 /* Same string. We can't insert. */
615 /* For each matching character pair, we need to disband the terminator.
616 * This splits the similar prefix into a single arc path.
617 * First, save the old values so we can move them to a new node.
618 * Next, for each loop:
619 * Take the current (invalid) node, and point it to the next arc base.
620 * Set the current node to the node at the next arc.
622 void *oldvalue = node->value;
623 bool oldvalset = node->valset;
624 if (*term == *keyptr)
626 while (*term == *keyptr)
628 /* Find the next free slot in the check array.
629 * This is the "vector base" essentially
631 q = x_check(trie, *term);
633 node = &base[curidx];
634 /* Point the node to the next new base */
636 node->mode = Node_Arc;
637 node->valset = false;
638 /* Advance the input stream and local variables */
640 curidx = q + charval(*term);
641 node = &base[curidx];
642 /* Make sure the new current node has its parent set. */
643 node->parent = lastidx;
644 node->mode = Node_Arc; /* Just in case we run x_check again */
645 *term = '\0'; /* Unmark the string table here */
650 node->valset = false;
652 /* We're done inserting new pairs. If one of them is exhausted,
653 * we take special shortcuts.
655 if (*term == '\0') //EX: BADGERHOUSE added over B -> ADGER.
657 /* First backpatch the current node - it ends the newly split terminator.
658 * In the example, this would mean the node is the production from R -> ?
659 * This node ends the old BADGER, so we set it here.
661 node->valset = oldvalset;
662 node->value = oldvalue;
664 /* The terminator was split up, but pieces of keyptr remain.
665 * We need to generate a new production, in this example, R -> H,
666 * with H being a terminator to OUSE. Thus we get:
667 * B,A,D,G,E,R*,H*->OUSE (* = value set).
668 * NOTE: parent was last set at the end of the while loop.
670 /* Get the new base and apply re-basing */
671 q = x_check(trie, *keyptr);
673 node = &base[curidx];
676 node->mode = Node_Arc;
678 /* Finish the final node */
679 curidx = q + charval(*keyptr);
680 node = &trie->base[curidx];
682 /* Optimize - don't add to string table if there's nothing more to eat */
685 node->mode = Node_Arc;
687 node->idx = x_addstring(trie, keyptr);
688 node->mode = Node_Term;
690 node->parent = lastidx;
693 } else if (*keyptr == '\0') { //EX: BADGER added over B -> ADGERHOUSE
694 /* First backpatch the current node - it ends newly split input string.
695 * This is the exact opposite of the above procedure.
700 /* Get the new base and apply re-basing */
701 q = x_check(trie, *term);
703 node = &base[curidx];
706 node->mode = Node_Arc;
708 /* Finish the final node */
709 curidx = q + charval(*term);
710 node = &trie->base[curidx];
712 /* Optimize - don't add to string table if there's nothing more to eat */
715 node->mode = Node_Arc;
717 node->idx = (term - trie->stringtab); /* Already in the string table! */
718 node->mode = Node_Term;
720 node->parent = lastidx;
721 node->valset = oldvalset;
722 node->value = oldvalue;
724 /* Finally, we have to create two new nodes instead of just one. */
725 node->mode = Node_Arc;
727 /* Get the new base and apply re-basing */
728 q = x_check2(trie, *keyptr, *term);
730 node = &base[curidx];
735 /* Re-create the old terminated node */
736 curidx = q + charval(*term);
737 node = &trie->base[curidx];
739 node->valset = oldvalset;
740 node->value = oldvalue;
741 node->parent = lastidx;
744 node->mode = Node_Arc;
746 node->mode = Node_Term;
747 node->idx = (term - trie->stringtab); /* Already in the string table! */
750 /* Create the new keyed input node */
751 curidx = q + charval(*keyptr);
752 node = &trie->base[curidx];
756 node->parent = lastidx;
759 node->mode = Node_Arc;
761 node->mode = Node_Term;
762 node->idx = x_addstring(trie, keyptr);
769 assert(node->mode == Node_Arc);
773 } while (*keyptr != '\0');
777 /* If we've exhausted the string and we have a valid reached node,
778 * the production rule already existed. Make sure it's valid to set first.
781 /* We have to be an Arc. If the last result was anything else, we would have returned a new
782 * production earlier.
784 assert(node->mode == Node_Arc);
786 /* Furthermore, if this is the last arc label in an arc, we should have a value set. */
789 assert(node->valset == true);
794 /* Insert is only possible if we have no production */