2 * ===============================================================
3 * SourceMod (C)2004-2007 AlliedModders LLC. All rights reserved.
4 * ===============================================================
6 * This file is not open source and may not be copied without explicit
7 * written permission of AlliedModders LLC. This file may not be redistributed
8 * in whole or significant part.
9 * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
20 * Double Array Trie algorithm, based on:
21 * An Efficient Implementation of Trie Structures, by
22 * Jun-ichi Aoe and Katsushi Maromoto, and Takashi Sato
23 * from Sofiware - Practice and Experience, Vol. 22(9), 695-721 (September 1992)
25 * A Trie is a simple data structure which stores strings as DFAs, with each
26 * transition state being a string entry. For example, observe the following strings:
28 * BAILOPAN, BAT, BACON, BACK
29 * These transition as the follow production rules:
40 * The standard implementation for this - using lists - gives a slow linear lookup, somewhere between
41 * O(N+M) or O(log n). A faster implementation is proposed in the paper above, which is based on compacting
42 * the transition states into two arrays. In the paper's implementation, two arrays are used, and thus it is
43 * called the "Double Array" algorithm. However, the CHECK array's size is maintained the same as BASE,
44 * so they can be combined into one structure. The array seems complex at first, but is very simple: it is a
45 * tree structure flattened out into a single vector. I am calling this implementation the Flat Array Trie.
47 * BASE[] is an array where each member is a node in the Trie. The node can either be UNUSED (empty), an ARC
48 * (containing an offset to the next set of ARCs), or a TERMINATOR (contains the rest of a string).
49 * Each node has an index which must be interpeted based on the node type. If the node is a TERMINATOR, then the
50 * index is an index into a string table, to find the rest of the string.
51 * If the node is an ARC, the index is another index into BASE. For each possible token that can follow the
52 * current token, the value of those tokens can be added to the index given in the ARC. Thus, given a current
53 * position and the next desired token, the current arc will jump to another arc which can contain either:
54 * 1) An invalid production (collision, no entry exists)
55 * 2) An empty production (no entry exists)
56 * 3) Another arc label (the string ends here or continues into more productions)
57 * 4) A TERMINATOR (the string ends here and contains an unused set of productions)
59 * So, given current offset N (starting at N=1), jumping to token C means the next offset will be:
61 * Thus, the next node will be at:
64 * This allows each ARC to specify the base offset for any of its ARC children, like a tree. Each node specifies
65 * its parent ARC -- so if an invalid offset is specified, the parent will not match, and thus no such derived
68 * This means that arrays can be laid out "sparsely," maximizing their usage. Note that N need not be related to
69 * 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
70 * insertion comes with a small deal of complexity. To insert a new set of tokens T, the algorithm finds a new
71 * BASE index N such that BASE[N+T[i]] is unused for each T[i]. Thus, indirection is not necessarily linear;
72 * traversing a chain of ARC nodes can _and will_ jump around BASE.
74 * Of course, given this level of flexibility in the array organization, there are collisions. This is largely
75 * where insertions become slow, as the old chain must be relocated before the new one is used. Relocation means
76 * finding one or more new base indexes, and this means traversing BASE until an acceptable index is found, such
77 * that each offset is unused (see description in previous paragraph).
79 * However, it is not insertion time we are concerned about. The "trie" name comes from reTRIEval. We are only
80 * concerned with lookup and deletion. Both lookup and deletion are O(k), where k is relative to the length of the
81 * input string. Note that it is best case O(1) and worst case O(k). Deleting the entire trie is always O(1).
85 * Optimization ideas for the future:
86 * 1) Store a reference count for each arc, with the count of sub-children.
87 * This could let us break out of "children searches" for case 4 easily.
88 * 2) Use a 'free list' so we can easily search the trie for free points.
89 * This would drastically speed up x_check*
94 Node_Unused = 0, /* Node is not being used (sparse) */
95 Node_Arc, /* Node is part of an arc and does not terminate */
96 Node_Term, /* Node is a terminator */
102 * For Node_Arc, this index stores the 'base' offset to the next arc chain.
103 * I.e. to jump from this arc to character C, it will be at base[idx+C].
104 * For Node_Term, this is an index into the string table.
109 * This contains the prior arc that we must have come from.
110 * For example, if arc 63 has a base jump of index 12, and we want to see if
111 * there is a valid character C, the parent of 12+C must be 63.
115 void *value; /* Value associated with this node */
116 NodeType mode; /* Current usage type of the node */
117 bool valset; /* Whether or not a value is set */
122 TrieNode *base; /* Base array for the sparse tables */
123 char *stringtab; /* String table pointer */
124 unsigned int baseSize; /* Size of the base array, in members */
125 unsigned int stSize; /* Size of the string table, in bytes */
126 unsigned int tail; /* Current unused offset into the string table */
129 inline unsigned char charval(char c)
131 return (unsigned char)c;
134 bool sm_trie_grow(Trie *trie)
136 /* The current # of nodes in the tree is trie->baseSize + 1 */
137 unsigned int curSize = trie->baseSize;
138 unsigned int newSize = curSize * 2;
140 //:TODO: Make functions calling this return failure if this fails
141 trie->base = (TrieNode *)realloc(trie->base, (newSize + 1) * sizeof(TrieNode));
147 memset(&trie->base[curSize+1], 0, (newSize - curSize) * sizeof(TrieNode));
148 trie->baseSize = newSize;
153 unsigned int x_check(Trie *trie, char c, unsigned int start=1)
155 TrieNode *base = trie->base;
156 unsigned char _c = charval(c);
157 unsigned int to_check = trie->baseSize - _c;
158 for (unsigned int i=start; i<=to_check; i++)
160 if (base[i+_c].mode == Node_Unused)
168 return x_check(trie, c, to_check+1);
171 unsigned int x_check2(Trie *trie, char c1, char c2, unsigned int start=1)
173 TrieNode *base = trie->base;
174 unsigned char _c1 = charval(c1);
175 unsigned char _c2 = charval(c2);
176 unsigned int to_check = trie->baseSize - (_c1 > _c2 ? _c1 : _c2);
177 for (unsigned int i=start; i<=to_check; i++)
179 if (base[i+_c1].mode == Node_Unused
180 && base[i+_c2].mode == Node_Unused)
188 return x_check2(trie, c1, c2, to_check+1);
191 unsigned int x_check_multi(Trie *trie,
192 unsigned int offsets[],
194 unsigned int start=1)
196 TrieNode *base = trie->base;
198 unsigned int to_check = trie->baseSize;
199 unsigned int highest = 0;
201 for (unsigned int i=0; i<count; i++)
203 if (offsets[i] > highest)
205 highest = offsets[i];
211 for (unsigned int i=start; i<=to_check; i++)
214 for (unsigned int j=0; j<count; j++)
216 cur = &base[i+offsets[j]];
217 if (cur->mode != Node_Unused)
231 return x_check_multi(trie, offsets, count, to_check+1);
234 unsigned int x_addstring(Trie *trie, const char *ptr)
236 size_t len = strlen(ptr) + 1;
238 if (trie->tail + len >= trie->stSize)
240 while (trie->tail + len >= trie->stSize)
244 trie->stringtab = (char *)realloc(trie->stringtab, trie->stSize);
247 unsigned int tail = trie->tail;
248 strcpy(&trie->stringtab[tail], ptr);
254 Trie *sm_trie_create()
258 t->base = (TrieNode *)malloc(sizeof(TrieNode) * (256 + 1));
259 t->stringtab = (char *)malloc(sizeof(char) * 256);
268 void sm_trie_clear(Trie *trie)
272 memset(trie->base, 0, sizeof(TrieNode) * (trie->baseSize + 1));
273 memset(trie->stringtab, 0, sizeof(char) * trie->stSize);
275 /* Sentinel root node */
276 trie->base[1].idx = 1;
277 trie->base[1].mode = Node_Arc;
278 trie->base[1].parent = 1;
281 void sm_trie_destroy(Trie *trie)
284 free(trie->stringtab);
288 bool sm_trie_delete(Trie *trie, const char *key)
290 unsigned int lastidx = 1; /* the last node index */
291 unsigned int curidx; /* current node index */
292 const char *keyptr = key; /* input stream at current token */
293 TrieNode *node = NULL; /* current node being processed */
294 TrieNode *base = trie->base;
301 /* Start traversing at the root node */
304 /* Find where the next character is, then advance */
305 curidx = base[lastidx].idx;
306 node = &base[curidx];
307 curidx += charval(*keyptr);
308 node = &base[curidx];
311 /* Check if this slot is supposed to be empty or is a collision */
312 if ((curidx > trie->baseSize) || node->mode == Node_Unused || node->parent != lastidx)
315 } else if (node->mode == Node_Term) {
316 char *term = &trie->stringtab[node->idx];
317 if (strcmp(keyptr, term) == 0)
323 } while (*keyptr != '\0');
325 assert(node != NULL);
332 node->valset = false;
338 bool sm_trie_retrieve(Trie *trie, const char *key, void **value)
340 unsigned int lastidx = 1; /* the last node index */
341 unsigned int curidx; /* current node index */
342 const char *keyptr = key; /* input stream at current token */
343 TrieNode *node = NULL; /* current node being processed */
344 TrieNode *base = trie->base;
351 /* Start traversing at the root node */
354 /* Find where the next character is, then advance */
355 curidx = base[lastidx].idx;
356 node = &base[curidx];
357 curidx += charval(*keyptr);
358 node = &base[curidx];
361 /* Check if this slot is supposed to be empty or is a collision */
362 if ((curidx > trie->baseSize) || node->mode == Node_Unused || node->parent != lastidx)
365 } else if (node->mode == Node_Term) {
366 char *term = &trie->stringtab[node->idx];
367 if (strcmp(keyptr, term) == 0)
373 } while (*keyptr != '\0');
375 assert(node != NULL);
384 *value = node->value;
390 bool sm_trie_insert(Trie *trie, const char *key, void *value)
392 unsigned int lastidx = 1; /* the last node index */
393 unsigned int curidx; /* current node index */
394 const char *keyptr = key; /* input stream at current token */
395 TrieNode *node = NULL; /* current node being processed */
396 TrieNode *basenode = NULL; /* current base node being processed */
397 unsigned int q; /* temporary var for x_check results */
398 TrieNode *base = trie->base;
399 unsigned int curoffs; /* current offset */
401 /* Do not handle empty strings for simplicity */
407 /* Start traversing at the root node (1) */
410 /* Find where the next character is, then advance */
411 curidx = base[lastidx].idx;
412 basenode = &base[curidx];
413 curoffs = charval(*keyptr);
415 node = &base[curidx];
418 /* Check if this slot is supposed to be empty. If so, we need to handle CASES 1/2:
419 * Insertion without collisions
421 if ( (curidx > trie->baseSize) || (node->mode == Node_Unused) )
423 if (curidx > trie->baseSize)
425 if (!sm_trie_grow(trie))
429 node = &trie->base[curidx];
431 node->parent = lastidx;
434 node->mode = Node_Arc;
436 node->idx = x_addstring(trie, keyptr);
437 node->mode = Node_Term;
443 } else if (node->parent != lastidx) {
444 /* Collision! We have to split up the tree here. CASE 4:
445 * Insertion when a new word is inserted with a collision.
446 * NOTE: This is the hardest case to handle. All below examples are based on:
447 * BACHELOR, BADGE, inserting BABY.
448 * The problematic production here is A -> B, where B is already being used.
450 * This process has to rotate one half of the 'A' arc. We generate two lists:
451 * Outgoing Arcs - Anything leaving this 'A'
452 * Incoming Arcs - Anything going to this 'A'
453 * Whichever list is smaller will be moved. Note that this works because the intersection
454 * affects both arc chains, and moving one will make the slot available to either.
458 /* Find every node arcing from the last node.
459 * I.e. for BACHELOR, BADGE, BABY,
460 * The arcs leaving A will be C and D, but our current node is B -> *.
461 * Thus, we use the last index (A) to find the base for arcs leaving A.
463 unsigned int outgoing_base = base[lastidx].idx;
464 unsigned int outgoing_list[256];
465 unsigned int outgoing_count = 0; /* count the current index here */
466 cur = &base[outgoing_base] + 1;
467 unsigned int outgoing_limit = 255;
469 if (outgoing_base + outgoing_limit > trie->baseSize)
471 outgoing_limit = trie->baseSize - outgoing_base;
474 for (unsigned int i=1; i<=outgoing_limit; i++,cur++)
476 if (cur->mode == Node_Unused || cur->parent != lastidx)
480 outgoing_list[outgoing_count++] = i;
482 outgoing_list[outgoing_count++] = curidx - outgoing_base;
484 /* Now we need to find all the arcs leaving our parent...
485 * Note: the inconsistency is the base of our parent.
487 assert(base[node->parent].mode == Node_Arc);
488 unsigned int incoming_list[256];
489 unsigned int incoming_base = base[node->parent].idx;
490 unsigned int incoming_count = 0;
491 unsigned int incoming_limit = 255;
492 cur = &base[incoming_base] + 1;
494 if (incoming_base + incoming_limit > trie->baseSize)
496 incoming_limit = trie->baseSize - incoming_base;
499 assert(incoming_limit > 0 && incoming_limit <= 255);
501 for (unsigned int i=1; i<=255; i++,cur++)
503 if (cur->mode == Node_Arc || cur->mode == Node_Term)
505 if (cur->parent == node->parent)
507 incoming_list[incoming_count++] = i;
512 if (incoming_count < outgoing_count + 1)
514 unsigned int q = x_check_multi(trie, incoming_list, incoming_count);
517 node = &base[curidx];
519 /* If we're incoming, we need to modify our parent */
520 base[node->parent].idx = q;
522 /* For each node in the "to move" list,
523 * Relocate the node's info to the new position.
525 unsigned int idx, newidx, oldidx;
526 for (unsigned int i=0; i<incoming_count; i++)
528 idx = incoming_list[i];
530 oldidx = incoming_base + idx;
531 if (oldidx == lastidx)
533 /* Important! Make sure we're not invalidating our sacred lastidx */
536 base[newidx] = base[oldidx];
537 assert(base[base[newidx].parent].mode == Node_Arc);
538 memset(&base[oldidx], 0, sizeof(TrieNode));
539 /* If we are not a terminator, we have children we must take care of */
540 if (base[newidx].mode == Node_Arc)
542 TrieNode *check_base = &base[base[newidx].idx] + 1;
543 for (unsigned int j=1; j<=255; j++, check_base++)
545 if (check_base->parent == oldidx)
547 check_base->parent = newidx;
553 unsigned int q = x_check_multi(trie, outgoing_list, outgoing_count);
556 node = &base[curidx];
558 /* If we're outgoing, we need to modify our own base */
559 base[lastidx].idx = q;
561 /* Take the last index (curidx) out of the list. Technically we are not moving this,
562 * since it's already being used by something else.
566 /* For each node in the "to move" list,
567 * Relocate the node's info to the new position.
569 unsigned int idx, newidx, oldidx;
570 for (unsigned int i=0; i<outgoing_count; i++)
572 idx = outgoing_list[i];
574 oldidx = outgoing_base + idx;
575 if (oldidx == lastidx)
577 /* Important! Make sure we're not invalidating our sacred lastidx */
580 base[newidx] = base[oldidx];
581 assert(base[base[newidx].parent].mode == Node_Arc);
582 memset(&base[oldidx], 0, sizeof(TrieNode));
583 /* If we are not a terminator, we have children we must take care of */
584 if (base[newidx].mode == Node_Arc)
586 TrieNode *check_base = &base[base[newidx].idx] + 1;
587 for (unsigned int j=1; j<=255; j++, check_base++)
589 if (check_base->parent == oldidx)
591 check_base->parent = newidx;
597 /* Take the invisible node and use it as our new node */
598 node = &base[q + outgoing_list[outgoing_count]];
601 /* We're finally done! */
602 node->parent = lastidx;
605 node->mode = Node_Arc;
607 node->idx = x_addstring(trie, keyptr);
608 node->mode = Node_Term;
615 /* See what's in the next node - special case if terminator! */
616 if (node->mode == Node_Term)
618 /* If we're a terminator, we need to handle CASE 3:
619 * Insertion when a terminating collision occurs
621 char *term = &trie->stringtab[node->idx];
622 /* Do an initial browsing to make sure they're not the same string */
623 if (strcmp(keyptr, term) == 0)
631 /* Same string. We can't insert. */
634 /* For each matching character pair, we need to disband the terminator.
635 * This splits the similar prefix into a single arc path.
636 * First, save the old values so we can move them to a new node.
637 * Next, for each loop:
638 * Take the current (invalid) node, and point it to the next arc base.
639 * Set the current node to the node at the next arc.
641 void *oldvalue = node->value;
642 bool oldvalset = node->valset;
643 if (*term == *keyptr)
645 while (*term == *keyptr)
647 /* Find the next free slot in the check array.
648 * This is the "vector base" essentially
650 q = x_check(trie, *term);
652 node = &base[curidx];
653 /* Point the node to the next new base */
655 node->mode = Node_Arc;
656 node->valset = false;
657 /* Advance the input stream and local variables */
659 curidx = q + charval(*term);
660 node = &base[curidx];
661 /* Make sure the new current node has its parent set. */
662 node->parent = lastidx;
663 node->mode = Node_Arc; /* Just in case we run x_check again */
664 *term = '\0'; /* Unmark the string table here */
669 node->valset = false;
671 /* We're done inserting new pairs. If one of them is exhausted,
672 * we take special shortcuts.
674 if (*term == '\0') //EX: BADGERHOUSE added over B -> ADGER.
676 /* First backpatch the current node - it ends the newly split terminator.
677 * In the example, this would mean the node is the production from R -> ?
678 * This node ends the old BADGER, so we set it here.
680 node->valset = oldvalset;
681 node->value = oldvalue;
683 /* The terminator was split up, but pieces of keyptr remain.
684 * We need to generate a new production, in this example, R -> H,
685 * with H being a terminator to OUSE. Thus we get:
686 * B,A,D,G,E,R*,H*->OUSE (* = value set).
687 * NOTE: parent was last set at the end of the while loop.
689 /* Get the new base and apply re-basing */
690 q = x_check(trie, *keyptr);
692 node = &base[curidx];
695 node->mode = Node_Arc;
697 /* Finish the final node */
698 curidx = q + charval(*keyptr);
699 node = &trie->base[curidx];
701 /* Optimize - don't add to string table if there's nothing more to eat */
704 node->mode = Node_Arc;
706 node->idx = x_addstring(trie, keyptr);
707 node->mode = Node_Term;
709 node->parent = lastidx;
712 } else if (*keyptr == '\0') { //EX: BADGER added over B -> ADGERHOUSE
713 /* First backpatch the current node - it ends newly split input string.
714 * This is the exact opposite of the above procedure.
719 /* Get the new base and apply re-basing */
720 q = x_check(trie, *term);
722 node = &base[curidx];
725 node->mode = Node_Arc;
727 /* Finish the final node */
728 curidx = q + charval(*term);
729 node = &trie->base[curidx];
731 /* Optimize - don't add to string table if there's nothing more to eat */
734 node->mode = Node_Arc;
736 node->idx = (term - trie->stringtab); /* Already in the string table! */
737 node->mode = Node_Term;
739 node->parent = lastidx;
740 node->valset = oldvalset;
741 node->value = oldvalue;
743 /* Finally, we have to create two new nodes instead of just one. */
744 node->mode = Node_Arc;
746 /* Get the new base and apply re-basing */
747 q = x_check2(trie, *keyptr, *term);
749 node = &base[curidx];
754 /* Re-create the old terminated node */
755 curidx = q + charval(*term);
756 node = &trie->base[curidx];
758 node->valset = oldvalset;
759 node->value = oldvalue;
760 node->parent = lastidx;
763 node->mode = Node_Arc;
765 node->mode = Node_Term;
766 node->idx = (term - trie->stringtab); /* Already in the string table! */
769 /* Create the new keyed input node */
770 curidx = q + charval(*keyptr);
771 node = &trie->base[curidx];
775 node->parent = lastidx;
778 node->mode = Node_Arc;
780 node->mode = Node_Term;
781 node->idx = x_addstring(trie, keyptr);
788 assert(node->mode == Node_Arc);
792 } while (*keyptr != '\0');
796 /* If we've exhausted the string and we have a valid reached node,
797 * the production rule already existed. Make sure it's valid to set first.
800 /* We have to be an Arc. If the last result was anything else, we would have returned a new
801 * production earlier.
803 assert(node->mode == Node_Arc);
805 /* Furthermore, if this is the last arc label in an arc, we should have a value set. */
808 assert(node->valset == true);
813 /* Insert is only possible if we have no production */