3 * =============================================================================
5 * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
38 * Double Array Trie algorithm, based on:
39 * An Efficient Implementation of Trie Structures, by
40 * Jun-ichi Aoe and Katsushi Maromoto, and Takashi Sato
41 * from Software - Practice and Experience, Vol. 22(9), 695-721 (September 1992)
43 * A Trie is a simple data structure which stores strings as DFAs, with each
44 * transition state being a string entry. For example, observe the following strings:
46 * BAILOPAN, BAT, BACON, BACK
47 * These transition as the follow production rules:
58 * The standard implementation for this - using lists - gives a slow linear lookup, somewhere between
59 * O(N+M) or O(log n). A faster implementation is proposed in the paper above, which is based on compacting
60 * the transition states into two arrays. In the paper's implementation, two arrays are used, and thus it is
61 * called the "Double Array" algorithm. However, the CHECK array's size is maintained the same as BASE,
62 * so they can be combined into one structure. The array seems complex at first, but is very simple: it is a
63 * tree structure flattened out into a single vector. I am calling this implementation the Flat Array Trie.
65 * BASE[] is an array where each member is a node in the Trie. The node can either be UNUSED (empty), an ARC
66 * (containing an offset to the next set of ARCs), or a TERMINATOR (contains the rest of a string).
67 * Each node has an index which must be interpreted based on the node type. If the node is a TERMINATOR, then the
68 * index is an index into a string table, to find the rest of the string.
69 * If the node is an ARC, the index is another index into BASE. For each possible token that can follow the
70 * current token, the value of those tokens can be added to the index given in the ARC. Thus, given a current
71 * position and the next desired token, the current arc will jump to another arc which can contain either:
72 * 1) An invalid production (collision, no entry exists)
73 * 2) An empty production (no entry exists)
74 * 3) Another arc label (the string ends here or continues into more productions)
75 * 4) A TERMINATOR (the string ends here and contains an unused set of productions)
77 * So, given current offset N (starting at N=1), jumping to token C means the next offset will be:
79 * Thus, the next node will be at:
82 * This allows each ARC to specify the base offset for any of its ARC children, like a tree. Each node specifies
83 * its parent ARC -- so if an invalid offset is specified, the parent will not match, and thus no such derived
86 * This means that arrays can be laid out "sparsely," maximizing their usage. Note that N need not be related to
87 * 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
88 * insertion comes with a small deal of complexity. To insert a new set of tokens T, the algorithm finds a new
89 * BASE index N such that BASE[N+T[i]] is unused for each T[i]. Thus, indirection is not necessarily linear;
90 * traversing a chain of ARC nodes can _and will_ jump around BASE.
92 * Of course, given this level of flexibility in the array organization, there are collisions. This is largely
93 * where insertions become slow, as the old chain must be relocated before the new one is used. Relocation means
94 * finding one or more new base indexes, and this means traversing BASE until an acceptable index is found, such
95 * that each offset is unused (see description in previous paragraph).
97 * However, it is not insertion time we are concerned about. The "trie" name comes from reTRIEval. We are only
98 * concerned with lookup and deletion. Both lookup and deletion are O(k), where k is relative to the length of the
99 * input string. Note that it is best case O(1) and worst case O(k). Deleting the entire trie is always O(1).
103 * Optimization ideas for the future:
104 * 1) Store a reference count for each arc, with the count of sub-children.
105 * This could let us break out of "children searches" for case 4 easily.
106 * 2) Use a 'free list' so we can easily search the trie for free points.
107 * This would drastically speed up x_check*
112 Node_Unused = 0, /* Node is not being used (sparse) */
113 Node_Arc, /* Node is part of an arc and does not terminate */
114 Node_Term, /* Node is a terminator */
120 * For Node_Arc, this index stores the 'base' offset to the next arc chain.
121 * I.e. to jump from this arc to character C, it will be at base[idx+C].
122 * For Node_Term, this is an index into the string table.
127 * This contains the prior arc that we must have come from.
128 * For example, if arc 63 has a base jump of index 12, and we want to see if
129 * there is a valid character C, the parent of 12+C must be 63.
133 void *value; /* Value associated with this node */
134 NodeType mode; /* Current usage type of the node */
135 bool valset; /* Whether or not a value is set */
140 TrieNode *base; /* Base array for the sparse tables */
141 char *stringtab; /* String table pointer */
142 unsigned int baseSize; /* Size of the base array, in members */
143 unsigned int stSize; /* Size of the string table, in bytes */
144 unsigned int tail; /* Current unused offset into the string table */
147 inline unsigned char charval(char c)
149 return (unsigned char)c;
152 bool sm_trie_grow(Trie *trie)
154 /* The current # of nodes in the tree is trie->baseSize + 1 */
155 unsigned int curSize = trie->baseSize;
156 unsigned int newSize = curSize * 2;
158 //:TODO: Make functions calling this return failure if this fails
159 trie->base = (TrieNode *)realloc(trie->base, (newSize + 1) * sizeof(TrieNode));
165 memset(&trie->base[curSize+1], 0, (newSize - curSize) * sizeof(TrieNode));
166 trie->baseSize = newSize;
171 unsigned int x_check(Trie *trie, char c, unsigned int start=1)
173 TrieNode *base = trie->base;
174 unsigned char _c = charval(c);
175 unsigned int to_check = trie->baseSize - _c;
176 for (unsigned int i=start; i<=to_check; i++)
178 if (base[i+_c].mode == Node_Unused)
186 return x_check(trie, c, to_check+1);
189 unsigned int x_check2(Trie *trie, char c1, char c2, unsigned int start=1)
191 TrieNode *base = trie->base;
192 unsigned char _c1 = charval(c1);
193 unsigned char _c2 = charval(c2);
194 unsigned int to_check = trie->baseSize - (_c1 > _c2 ? _c1 : _c2);
195 for (unsigned int i=start; i<=to_check; i++)
197 if (base[i+_c1].mode == Node_Unused
198 && base[i+_c2].mode == Node_Unused)
206 return x_check2(trie, c1, c2, to_check+1);
209 unsigned int x_check_multi(Trie *trie,
210 unsigned int offsets[],
212 unsigned int start=1)
214 TrieNode *base = trie->base;
216 unsigned int to_check = trie->baseSize;
217 unsigned int highest = 0;
219 for (unsigned int i=0; i<count; i++)
221 if (offsets[i] > highest)
223 highest = offsets[i];
229 for (unsigned int i=start; i<=to_check; i++)
232 for (unsigned int j=0; j<count; j++)
234 cur = &base[i+offsets[j]];
235 if (cur->mode != Node_Unused)
249 return x_check_multi(trie, offsets, count, to_check+1);
252 unsigned int x_addstring(Trie *trie, const char *ptr)
254 size_t len = strlen(ptr) + 1;
256 if (trie->tail + len >= trie->stSize)
258 while (trie->tail + len >= trie->stSize)
262 trie->stringtab = (char *)realloc(trie->stringtab, trie->stSize);
265 unsigned int tail = trie->tail;
266 strcpy(&trie->stringtab[tail], ptr);
272 Trie *sm_trie_create()
276 t->base = (TrieNode *)malloc(sizeof(TrieNode) * (256 + 1));
277 t->stringtab = (char *)malloc(sizeof(char) * 256);
286 void sm_trie_clear(Trie *trie)
290 memset(trie->base, 0, sizeof(TrieNode) * (trie->baseSize + 1));
291 memset(trie->stringtab, 0, sizeof(char) * trie->stSize);
293 /* Sentinel root node */
294 trie->base[1].idx = 1;
295 trie->base[1].mode = Node_Arc;
296 trie->base[1].parent = 1;
299 void sm_trie_destroy(Trie *trie)
302 free(trie->stringtab);
306 bool sm_trie_delete(Trie *trie, const char *key)
308 unsigned int lastidx = 1; /* the last node index */
309 unsigned int curidx; /* current node index */
310 const char *keyptr = key; /* input stream at current token */
311 TrieNode *node = NULL; /* current node being processed */
312 TrieNode *base = trie->base;
319 /* Start traversing at the root node */
322 /* Find where the next character is, then advance */
323 curidx = base[lastidx].idx;
324 node = &base[curidx];
325 curidx += charval(*keyptr);
326 node = &base[curidx];
329 /* Check if this slot is supposed to be empty or is a collision */
330 if ((curidx > trie->baseSize) || node->mode == Node_Unused || node->parent != lastidx)
333 } else if (node->mode == Node_Term) {
334 char *term = &trie->stringtab[node->idx];
335 if (strcmp(keyptr, term) == 0)
341 } while (*keyptr != '\0');
343 assert(node != NULL);
350 node->valset = false;
356 bool sm_trie_retrieve(Trie *trie, const char *key, void **value)
358 unsigned int lastidx = 1; /* the last node index */
359 unsigned int curidx; /* current node index */
360 const char *keyptr = key; /* input stream at current token */
361 TrieNode *node = NULL; /* current node being processed */
362 TrieNode *base = trie->base;
369 /* Start traversing at the root node */
372 /* Find where the next character is, then advance */
373 curidx = base[lastidx].idx;
374 node = &base[curidx];
375 curidx += charval(*keyptr);
376 node = &base[curidx];
379 /* Check if this slot is supposed to be empty or is a collision */
380 if ((curidx > trie->baseSize) || node->mode == Node_Unused || node->parent != lastidx)
383 } else if (node->mode == Node_Term) {
384 char *term = &trie->stringtab[node->idx];
385 if (strcmp(keyptr, term) == 0)
391 } while (*keyptr != '\0');
393 assert(node != NULL);
402 *value = node->value;
408 bool sm_trie_add(Trie *trie, const char *key, void *value, bool replace_allowed)
410 unsigned int lastidx = 1; /* the last node index */
411 unsigned int curidx; /* current node index */
412 const char *keyptr = key; /* input stream at current token */
413 TrieNode *node = NULL; /* current node being processed */
414 TrieNode *basenode = NULL; /* current base node being processed */
415 unsigned int q; /* temporary var for x_check results */
416 TrieNode *base = trie->base;
417 unsigned int curoffs; /* current offset */
419 /* Do not handle empty strings for simplicity */
425 /* Start traversing at the root node (1) */
428 /* Find where the next character is, then advance */
429 curidx = base[lastidx].idx;
430 basenode = &base[curidx];
431 curoffs = charval(*keyptr);
433 node = &base[curidx];
436 /* Check if this slot is supposed to be empty. If so, we need to handle CASES 1/2:
437 * Insertion without collisions
439 if ( (curidx > trie->baseSize) || (node->mode == Node_Unused) )
441 if (curidx > trie->baseSize)
443 if (!sm_trie_grow(trie))
447 node = &trie->base[curidx];
449 node->parent = lastidx;
452 node->mode = Node_Arc;
454 node->idx = x_addstring(trie, keyptr);
455 node->mode = Node_Term;
461 } else if (node->parent != lastidx) {
462 /* Collision! We have to split up the tree here. CASE 4:
463 * Insertion when a new word is inserted with a collision.
464 * NOTE: This is the hardest case to handle. All below examples are based on:
465 * BACHELOR, BADGE, inserting BABY.
466 * The problematic production here is A -> B, where B is already being used.
468 * This process has to rotate one half of the 'A' arc. We generate two lists:
469 * Outgoing Arcs - Anything leaving this 'A'
470 * Incoming Arcs - Anything going to this 'A'
471 * Whichever list is smaller will be moved. Note that this works because the intersection
472 * affects both arc chains, and moving one will make the slot available to either.
476 /* Find every node arcing from the last node.
477 * I.e. for BACHELOR, BADGE, BABY,
478 * The arcs leaving A will be C and D, but our current node is B -> *.
479 * Thus, we use the last index (A) to find the base for arcs leaving A.
481 unsigned int outgoing_base = base[lastidx].idx;
482 unsigned int outgoing_list[256];
483 unsigned int outgoing_count = 0; /* count the current index here */
484 cur = &base[outgoing_base] + 1;
485 unsigned int outgoing_limit = 255;
487 if (outgoing_base + outgoing_limit > trie->baseSize)
489 outgoing_limit = trie->baseSize - outgoing_base;
492 for (unsigned int i=1; i<=outgoing_limit; i++,cur++)
494 if (cur->mode == Node_Unused || cur->parent != lastidx)
498 outgoing_list[outgoing_count++] = i;
500 outgoing_list[outgoing_count++] = curidx - outgoing_base;
502 /* Now we need to find all the arcs leaving our parent...
503 * Note: the inconsistency is the base of our parent.
505 assert(base[node->parent].mode == Node_Arc);
506 unsigned int incoming_list[256];
507 unsigned int incoming_base = base[node->parent].idx;
508 unsigned int incoming_count = 0;
509 unsigned int incoming_limit = 255;
510 cur = &base[incoming_base] + 1;
512 if (incoming_base + incoming_limit > trie->baseSize)
514 incoming_limit = trie->baseSize - incoming_base;
517 assert(incoming_limit > 0 && incoming_limit <= 255);
519 for (unsigned int i=1; i<=incoming_limit; i++,cur++)
521 if (cur->mode == Node_Arc || cur->mode == Node_Term)
523 if (cur->parent == node->parent)
525 incoming_list[incoming_count++] = i;
530 if (incoming_count < outgoing_count + 1)
532 unsigned int q = x_check_multi(trie, incoming_list, incoming_count);
535 node = &base[curidx];
537 /* If we're incoming, we need to modify our parent */
538 base[node->parent].idx = q;
540 /* For each node in the "to move" list,
541 * Relocate the node's info to the new position.
543 unsigned int idx, newidx, oldidx;
544 for (unsigned int i=0; i<incoming_count; i++)
546 idx = incoming_list[i];
548 oldidx = incoming_base + idx;
549 if (oldidx == lastidx)
551 /* Important! Make sure we're not invalidating our sacred lastidx */
554 base[newidx] = base[oldidx];
555 assert(base[base[newidx].parent].mode == Node_Arc);
556 memset(&base[oldidx], 0, sizeof(TrieNode));
557 /* If we are not a terminator, we have children we must take care of */
558 if (base[newidx].mode == Node_Arc)
560 TrieNode *check_base = &base[base[newidx].idx] + 1;
561 outgoing_limit = (base + trie->baseSize + 1) - check_base;
562 if (outgoing_limit > 255)
564 outgoing_limit = 255;
566 for (unsigned int j=1; j<=outgoing_limit; j++, check_base++)
568 if (check_base->parent == oldidx)
570 check_base->parent = newidx;
576 unsigned int q = x_check_multi(trie, outgoing_list, outgoing_count);
579 node = &base[curidx];
581 /* If we're outgoing, we need to modify our own base */
582 base[lastidx].idx = q;
584 /* Take the last index (curidx) out of the list. Technically we are not moving this,
585 * since it's already being used by something else.
589 /* For each node in the "to move" list,
590 * Relocate the node's info to the new position.
592 unsigned int idx, newidx, oldidx;
593 for (unsigned int i=0; i<outgoing_count; i++)
595 idx = outgoing_list[i];
597 oldidx = outgoing_base + idx;
598 if (oldidx == lastidx)
600 /* Important! Make sure we're not invalidating our sacred lastidx */
603 base[newidx] = base[oldidx];
604 assert(base[base[newidx].parent].mode == Node_Arc);
605 memset(&base[oldidx], 0, sizeof(TrieNode));
606 /* If we are not a terminator, we have children we must take care of */
607 if (base[newidx].mode == Node_Arc)
609 TrieNode *check_base = &base[base[newidx].idx] + 1;
610 outgoing_limit = (base + trie->baseSize + 1) - check_base;
611 if (outgoing_limit > 255)
613 outgoing_limit = 255;
615 for (unsigned int j=1; j<=outgoing_limit; j++, check_base++)
617 if (check_base->parent == oldidx)
619 check_base->parent = newidx;
625 /* Take the invisible node and use it as our new node */
626 node = &base[q + outgoing_list[outgoing_count]];
629 /* We're finally done! */
630 node->parent = lastidx;
633 node->mode = Node_Arc;
635 node->idx = x_addstring(trie, keyptr);
636 node->mode = Node_Term;
643 /* See what's in the next node - special case if terminator! */
644 if (node->mode == Node_Term)
646 /* If we're a terminator, we need to handle CASE 3:
647 * Insertion when a terminating collision occurs
649 char *term = &trie->stringtab[node->idx];
650 /* Do an initial browsing to make sure they're not the same string */
651 if (strcmp(keyptr, term) == 0)
653 if (!node->valset || replace_allowed)
659 /* Same string. We can't insert. */
662 /* For each matching character pair, we need to disband the terminator.
663 * This splits the similar prefix into a single arc path.
664 * First, save the old values so we can move them to a new node.
665 * Next, for each loop:
666 * Take the current (invalid) node, and point it to the next arc base.
667 * Set the current node to the node at the next arc.
669 void *oldvalue = node->value;
670 bool oldvalset = node->valset;
671 if (*term == *keyptr)
673 while (*term == *keyptr)
675 /* Find the next free slot in the check array.
676 * This is the "vector base" essentially
678 q = x_check(trie, *term);
680 node = &base[curidx];
681 /* Point the node to the next new base */
683 node->mode = Node_Arc;
684 node->valset = false;
685 /* Advance the input stream and local variables */
687 curidx = q + charval(*term);
688 node = &base[curidx];
689 /* Make sure the new current node has its parent set. */
690 node->parent = lastidx;
691 node->mode = Node_Arc; /* Just in case we run x_check again */
692 *term = '\0'; /* Unmark the string table here */
697 node->valset = false;
699 /* We're done inserting new pairs. If one of them is exhausted,
700 * we take special shortcuts.
702 if (*term == '\0') //EX: BADGERHOUSE added over B -> ADGER.
704 /* First backpatch the current node - it ends the newly split terminator.
705 * In the example, this would mean the node is the production from R -> ?
706 * This node ends the old BADGER, so we set it here.
708 node->valset = oldvalset;
709 node->value = oldvalue;
711 /* The terminator was split up, but pieces of keyptr remain.
712 * We need to generate a new production, in this example, R -> H,
713 * with H being a terminator to OUSE. Thus we get:
714 * B,A,D,G,E,R*,H*->OUSE (* = value set).
715 * NOTE: parent was last set at the end of the while loop.
717 /* Get the new base and apply re-basing */
718 q = x_check(trie, *keyptr);
720 node = &base[curidx];
723 node->mode = Node_Arc;
725 /* Finish the final node */
726 curidx = q + charval(*keyptr);
727 node = &trie->base[curidx];
729 /* Optimize - don't add to string table if there's nothing more to eat */
732 node->mode = Node_Arc;
734 node->idx = x_addstring(trie, keyptr);
735 node->mode = Node_Term;
737 node->parent = lastidx;
740 } else if (*keyptr == '\0') { //EX: BADGER added over B -> ADGERHOUSE
741 /* First backpatch the current node - it ends newly split input string.
742 * This is the exact opposite of the above procedure.
747 /* Get the new base and apply re-basing */
748 q = x_check(trie, *term);
750 node = &base[curidx];
753 node->mode = Node_Arc;
755 /* Finish the final node */
756 curidx = q + charval(*term);
757 node = &trie->base[curidx];
759 /* Optimize - don't add to string table if there's nothing more to eat */
762 node->mode = Node_Arc;
764 node->idx = (term - trie->stringtab); /* Already in the string table! */
765 node->mode = Node_Term;
767 node->parent = lastidx;
768 node->valset = oldvalset;
769 node->value = oldvalue;
771 /* Finally, we have to create two new nodes instead of just one. */
772 node->mode = Node_Arc;
774 /* Get the new base and apply re-basing */
775 q = x_check2(trie, *keyptr, *term);
777 node = &base[curidx];
782 /* Re-create the old terminated node */
783 curidx = q + charval(*term);
784 node = &trie->base[curidx];
786 node->valset = oldvalset;
787 node->value = oldvalue;
788 node->parent = lastidx;
791 node->mode = Node_Arc;
793 node->mode = Node_Term;
794 node->idx = (term - trie->stringtab); /* Already in the string table! */
797 /* Create the new keyed input node */
798 curidx = q + charval(*keyptr);
799 node = &trie->base[curidx];
803 node->parent = lastidx;
806 node->mode = Node_Arc;
808 node->mode = Node_Term;
809 node->idx = x_addstring(trie, keyptr);
816 assert(node->mode == Node_Arc);
820 } while (*keyptr != '\0');
824 /* If we've exhausted the string and we have a valid reached node,
825 * the production rule already existed. Make sure it's valid to set first.
828 /* We have to be an Arc. If the last result was anything else, we would have returned a new
829 * production earlier.
831 assert(node->mode == Node_Arc);
833 if (!node->valset || replace_allowed)
835 /* Insert is only possible if we have no production */
844 bool sm_trie_insert(Trie *trie, const char *key, void *value)
846 return sm_trie_add(trie, key, value, false);
849 bool sm_trie_replace(Trie *trie, const char *key, void *value)
851 return sm_trie_add(trie, key, value, true);