3 * ================================================================
5 * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
6 * ================================================================
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License,
10 * version 3.0, as published by the Free Software Foundation.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to
21 * link the code of this program (as well as its derivative works) to
22 * "Half-Life 2," the "Source Engine," the "SourcePawn JIT," and any
23 * Game MODs that run on software by the Valve Corporation. You must
24 * obey the GNU General Public License in all respects for all other
25 * code used. Additionally, AlliedModders LLC grants this exception
26 * to all derivative works. AlliedModders LLC defines further
27 * exceptions, found in LICENSE.txt (as of this writing, version
28 * JULY-31-2007), or <http://www.sourcemod.net/license.php>.
39 * Double Array Trie algorithm, based on:
40 * An Efficient Implementation of Trie Structures, by
41 * Jun-ichi Aoe and Katsushi Maromoto, and Takashi Sato
42 * from Software - Practice and Experience, Vol. 22(9), 695-721 (September 1992)
44 * A Trie is a simple data structure which stores strings as DFAs, with each
45 * transition state being a string entry. For example, observe the following strings:
47 * BAILOPAN, BAT, BACON, BACK
48 * These transition as the follow production rules:
59 * The standard implementation for this - using lists - gives a slow linear lookup, somewhere between
60 * O(N+M) or O(log n). A faster implementation is proposed in the paper above, which is based on compacting
61 * the transition states into two arrays. In the paper's implementation, two arrays are used, and thus it is
62 * called the "Double Array" algorithm. However, the CHECK array's size is maintained the same as BASE,
63 * so they can be combined into one structure. The array seems complex at first, but is very simple: it is a
64 * tree structure flattened out into a single vector. I am calling this implementation the Flat Array Trie.
66 * BASE[] is an array where each member is a node in the Trie. The node can either be UNUSED (empty), an ARC
67 * (containing an offset to the next set of ARCs), or a TERMINATOR (contains the rest of a string).
68 * Each node has an index which must be interpreted based on the node type. If the node is a TERMINATOR, then the
69 * index is an index into a string table, to find the rest of the string.
70 * If the node is an ARC, the index is another index into BASE. For each possible token that can follow the
71 * current token, the value of those tokens can be added to the index given in the ARC. Thus, given a current
72 * position and the next desired token, the current arc will jump to another arc which can contain either:
73 * 1) An invalid production (collision, no entry exists)
74 * 2) An empty production (no entry exists)
75 * 3) Another arc label (the string ends here or continues into more productions)
76 * 4) A TERMINATOR (the string ends here and contains an unused set of productions)
78 * So, given current offset N (starting at N=1), jumping to token C means the next offset will be:
80 * Thus, the next node will be at:
83 * This allows each ARC to specify the base offset for any of its ARC children, like a tree. Each node specifies
84 * its parent ARC -- so if an invalid offset is specified, the parent will not match, and thus no such derived
87 * This means that arrays can be laid out "sparsely," maximizing their usage. Note that N need not be related to
88 * 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
89 * insertion comes with a small deal of complexity. To insert a new set of tokens T, the algorithm finds a new
90 * BASE index N such that BASE[N+T[i]] is unused for each T[i]. Thus, indirection is not necessarily linear;
91 * traversing a chain of ARC nodes can _and will_ jump around BASE.
93 * Of course, given this level of flexibility in the array organization, there are collisions. This is largely
94 * where insertions become slow, as the old chain must be relocated before the new one is used. Relocation means
95 * finding one or more new base indexes, and this means traversing BASE until an acceptable index is found, such
96 * that each offset is unused (see description in previous paragraph).
98 * However, it is not insertion time we are concerned about. The "trie" name comes from reTRIEval. We are only
99 * concerned with lookup and deletion. Both lookup and deletion are O(k), where k is relative to the length of the
100 * input string. Note that it is best case O(1) and worst case O(k). Deleting the entire trie is always O(1).
104 * Optimization ideas for the future:
105 * 1) Store a reference count for each arc, with the count of sub-children.
106 * This could let us break out of "children searches" for case 4 easily.
107 * 2) Use a 'free list' so we can easily search the trie for free points.
108 * This would drastically speed up x_check*
113 Node_Unused = 0, /* Node is not being used (sparse) */
114 Node_Arc, /* Node is part of an arc and does not terminate */
115 Node_Term, /* Node is a terminator */
121 * For Node_Arc, this index stores the 'base' offset to the next arc chain.
122 * I.e. to jump from this arc to character C, it will be at base[idx+C].
123 * For Node_Term, this is an index into the string table.
128 * This contains the prior arc that we must have come from.
129 * For example, if arc 63 has a base jump of index 12, and we want to see if
130 * there is a valid character C, the parent of 12+C must be 63.
134 void *value; /* Value associated with this node */
135 NodeType mode; /* Current usage type of the node */
136 bool valset; /* Whether or not a value is set */
141 TrieNode *base; /* Base array for the sparse tables */
142 char *stringtab; /* String table pointer */
143 unsigned int baseSize; /* Size of the base array, in members */
144 unsigned int stSize; /* Size of the string table, in bytes */
145 unsigned int tail; /* Current unused offset into the string table */
148 inline unsigned char charval(char c)
150 return (unsigned char)c;
153 bool sm_trie_grow(Trie *trie)
155 /* The current # of nodes in the tree is trie->baseSize + 1 */
156 unsigned int curSize = trie->baseSize;
157 unsigned int newSize = curSize * 2;
159 //:TODO: Make functions calling this return failure if this fails
160 trie->base = (TrieNode *)realloc(trie->base, (newSize + 1) * sizeof(TrieNode));
166 memset(&trie->base[curSize+1], 0, (newSize - curSize) * sizeof(TrieNode));
167 trie->baseSize = newSize;
172 unsigned int x_check(Trie *trie, char c, unsigned int start=1)
174 TrieNode *base = trie->base;
175 unsigned char _c = charval(c);
176 unsigned int to_check = trie->baseSize - _c;
177 for (unsigned int i=start; i<=to_check; i++)
179 if (base[i+_c].mode == Node_Unused)
187 return x_check(trie, c, to_check+1);
190 unsigned int x_check2(Trie *trie, char c1, char c2, unsigned int start=1)
192 TrieNode *base = trie->base;
193 unsigned char _c1 = charval(c1);
194 unsigned char _c2 = charval(c2);
195 unsigned int to_check = trie->baseSize - (_c1 > _c2 ? _c1 : _c2);
196 for (unsigned int i=start; i<=to_check; i++)
198 if (base[i+_c1].mode == Node_Unused
199 && base[i+_c2].mode == Node_Unused)
207 return x_check2(trie, c1, c2, to_check+1);
210 unsigned int x_check_multi(Trie *trie,
211 unsigned int offsets[],
213 unsigned int start=1)
215 TrieNode *base = trie->base;
217 unsigned int to_check = trie->baseSize;
218 unsigned int highest = 0;
220 for (unsigned int i=0; i<count; i++)
222 if (offsets[i] > highest)
224 highest = offsets[i];
230 for (unsigned int i=start; i<=to_check; i++)
233 for (unsigned int j=0; j<count; j++)
235 cur = &base[i+offsets[j]];
236 if (cur->mode != Node_Unused)
250 return x_check_multi(trie, offsets, count, to_check+1);
253 unsigned int x_addstring(Trie *trie, const char *ptr)
255 size_t len = strlen(ptr) + 1;
257 if (trie->tail + len >= trie->stSize)
259 while (trie->tail + len >= trie->stSize)
263 trie->stringtab = (char *)realloc(trie->stringtab, trie->stSize);
266 unsigned int tail = trie->tail;
267 strcpy(&trie->stringtab[tail], ptr);
273 Trie *sm_trie_create()
277 t->base = (TrieNode *)malloc(sizeof(TrieNode) * (256 + 1));
278 t->stringtab = (char *)malloc(sizeof(char) * 256);
287 void sm_trie_clear(Trie *trie)
291 memset(trie->base, 0, sizeof(TrieNode) * (trie->baseSize + 1));
292 memset(trie->stringtab, 0, sizeof(char) * trie->stSize);
294 /* Sentinel root node */
295 trie->base[1].idx = 1;
296 trie->base[1].mode = Node_Arc;
297 trie->base[1].parent = 1;
300 void sm_trie_destroy(Trie *trie)
303 free(trie->stringtab);
307 bool sm_trie_delete(Trie *trie, const char *key)
309 unsigned int lastidx = 1; /* the last node index */
310 unsigned int curidx; /* current node index */
311 const char *keyptr = key; /* input stream at current token */
312 TrieNode *node = NULL; /* current node being processed */
313 TrieNode *base = trie->base;
320 /* Start traversing at the root node */
323 /* Find where the next character is, then advance */
324 curidx = base[lastidx].idx;
325 node = &base[curidx];
326 curidx += charval(*keyptr);
327 node = &base[curidx];
330 /* Check if this slot is supposed to be empty or is a collision */
331 if ((curidx > trie->baseSize) || node->mode == Node_Unused || node->parent != lastidx)
334 } else if (node->mode == Node_Term) {
335 char *term = &trie->stringtab[node->idx];
336 if (strcmp(keyptr, term) == 0)
342 } while (*keyptr != '\0');
344 assert(node != NULL);
351 node->valset = false;
357 bool sm_trie_retrieve(Trie *trie, const char *key, void **value)
359 unsigned int lastidx = 1; /* the last node index */
360 unsigned int curidx; /* current node index */
361 const char *keyptr = key; /* input stream at current token */
362 TrieNode *node = NULL; /* current node being processed */
363 TrieNode *base = trie->base;
370 /* Start traversing at the root node */
373 /* Find where the next character is, then advance */
374 curidx = base[lastidx].idx;
375 node = &base[curidx];
376 curidx += charval(*keyptr);
377 node = &base[curidx];
380 /* Check if this slot is supposed to be empty or is a collision */
381 if ((curidx > trie->baseSize) || node->mode == Node_Unused || node->parent != lastidx)
384 } else if (node->mode == Node_Term) {
385 char *term = &trie->stringtab[node->idx];
386 if (strcmp(keyptr, term) == 0)
392 } while (*keyptr != '\0');
394 assert(node != NULL);
403 *value = node->value;
409 bool sm_trie_add(Trie *trie, const char *key, void *value, bool replace_allowed)
411 unsigned int lastidx = 1; /* the last node index */
412 unsigned int curidx; /* current node index */
413 const char *keyptr = key; /* input stream at current token */
414 TrieNode *node = NULL; /* current node being processed */
415 TrieNode *basenode = NULL; /* current base node being processed */
416 unsigned int q; /* temporary var for x_check results */
417 TrieNode *base = trie->base;
418 unsigned int curoffs; /* current offset */
420 /* Do not handle empty strings for simplicity */
426 /* Start traversing at the root node (1) */
429 /* Find where the next character is, then advance */
430 curidx = base[lastidx].idx;
431 basenode = &base[curidx];
432 curoffs = charval(*keyptr);
434 node = &base[curidx];
437 /* Check if this slot is supposed to be empty. If so, we need to handle CASES 1/2:
438 * Insertion without collisions
440 if ( (curidx > trie->baseSize) || (node->mode == Node_Unused) )
442 if (curidx > trie->baseSize)
444 if (!sm_trie_grow(trie))
448 node = &trie->base[curidx];
450 node->parent = lastidx;
453 node->mode = Node_Arc;
455 node->idx = x_addstring(trie, keyptr);
456 node->mode = Node_Term;
462 } else if (node->parent != lastidx) {
463 /* Collision! We have to split up the tree here. CASE 4:
464 * Insertion when a new word is inserted with a collision.
465 * NOTE: This is the hardest case to handle. All below examples are based on:
466 * BACHELOR, BADGE, inserting BABY.
467 * The problematic production here is A -> B, where B is already being used.
469 * This process has to rotate one half of the 'A' arc. We generate two lists:
470 * Outgoing Arcs - Anything leaving this 'A'
471 * Incoming Arcs - Anything going to this 'A'
472 * Whichever list is smaller will be moved. Note that this works because the intersection
473 * affects both arc chains, and moving one will make the slot available to either.
477 /* Find every node arcing from the last node.
478 * I.e. for BACHELOR, BADGE, BABY,
479 * The arcs leaving A will be C and D, but our current node is B -> *.
480 * Thus, we use the last index (A) to find the base for arcs leaving A.
482 unsigned int outgoing_base = base[lastidx].idx;
483 unsigned int outgoing_list[256];
484 unsigned int outgoing_count = 0; /* count the current index here */
485 cur = &base[outgoing_base] + 1;
486 unsigned int outgoing_limit = 255;
488 if (outgoing_base + outgoing_limit > trie->baseSize)
490 outgoing_limit = trie->baseSize - outgoing_base;
493 for (unsigned int i=1; i<=outgoing_limit; i++,cur++)
495 if (cur->mode == Node_Unused || cur->parent != lastidx)
499 outgoing_list[outgoing_count++] = i;
501 outgoing_list[outgoing_count++] = curidx - outgoing_base;
503 /* Now we need to find all the arcs leaving our parent...
504 * Note: the inconsistency is the base of our parent.
506 assert(base[node->parent].mode == Node_Arc);
507 unsigned int incoming_list[256];
508 unsigned int incoming_base = base[node->parent].idx;
509 unsigned int incoming_count = 0;
510 unsigned int incoming_limit = 255;
511 cur = &base[incoming_base] + 1;
513 if (incoming_base + incoming_limit > trie->baseSize)
515 incoming_limit = trie->baseSize - incoming_base;
518 assert(incoming_limit > 0 && incoming_limit <= 255);
520 for (unsigned int i=1; i<=incoming_limit; i++,cur++)
522 if (cur->mode == Node_Arc || cur->mode == Node_Term)
524 if (cur->parent == node->parent)
526 incoming_list[incoming_count++] = i;
531 if (incoming_count < outgoing_count + 1)
533 unsigned int q = x_check_multi(trie, incoming_list, incoming_count);
536 node = &base[curidx];
538 /* If we're incoming, we need to modify our parent */
539 base[node->parent].idx = q;
541 /* For each node in the "to move" list,
542 * Relocate the node's info to the new position.
544 unsigned int idx, newidx, oldidx;
545 for (unsigned int i=0; i<incoming_count; i++)
547 idx = incoming_list[i];
549 oldidx = incoming_base + idx;
550 if (oldidx == lastidx)
552 /* Important! Make sure we're not invalidating our sacred lastidx */
555 base[newidx] = base[oldidx];
556 assert(base[base[newidx].parent].mode == Node_Arc);
557 memset(&base[oldidx], 0, sizeof(TrieNode));
558 /* If we are not a terminator, we have children we must take care of */
559 if (base[newidx].mode == Node_Arc)
561 TrieNode *check_base = &base[base[newidx].idx] + 1;
562 for (unsigned int j=1; j<=255; j++, check_base++)
564 if (check_base->parent == oldidx)
566 check_base->parent = newidx;
572 unsigned int q = x_check_multi(trie, outgoing_list, outgoing_count);
575 node = &base[curidx];
577 /* If we're outgoing, we need to modify our own base */
578 base[lastidx].idx = q;
580 /* Take the last index (curidx) out of the list. Technically we are not moving this,
581 * since it's already being used by something else.
585 /* For each node in the "to move" list,
586 * Relocate the node's info to the new position.
588 unsigned int idx, newidx, oldidx;
589 for (unsigned int i=0; i<outgoing_count; i++)
591 idx = outgoing_list[i];
593 oldidx = outgoing_base + idx;
594 if (oldidx == lastidx)
596 /* Important! Make sure we're not invalidating our sacred lastidx */
599 base[newidx] = base[oldidx];
600 assert(base[base[newidx].parent].mode == Node_Arc);
601 memset(&base[oldidx], 0, sizeof(TrieNode));
602 /* If we are not a terminator, we have children we must take care of */
603 if (base[newidx].mode == Node_Arc)
605 TrieNode *check_base = &base[base[newidx].idx] + 1;
606 for (unsigned int j=1; j<=255; j++, check_base++)
608 if (check_base->parent == oldidx)
610 check_base->parent = newidx;
616 /* Take the invisible node and use it as our new node */
617 node = &base[q + outgoing_list[outgoing_count]];
620 /* We're finally done! */
621 node->parent = lastidx;
624 node->mode = Node_Arc;
626 node->idx = x_addstring(trie, keyptr);
627 node->mode = Node_Term;
634 /* See what's in the next node - special case if terminator! */
635 if (node->mode == Node_Term)
637 /* If we're a terminator, we need to handle CASE 3:
638 * Insertion when a terminating collision occurs
640 char *term = &trie->stringtab[node->idx];
641 /* Do an initial browsing to make sure they're not the same string */
642 if (strcmp(keyptr, term) == 0)
644 if (!node->valset || replace_allowed)
650 /* Same string. We can't insert. */
653 /* For each matching character pair, we need to disband the terminator.
654 * This splits the similar prefix into a single arc path.
655 * First, save the old values so we can move them to a new node.
656 * Next, for each loop:
657 * Take the current (invalid) node, and point it to the next arc base.
658 * Set the current node to the node at the next arc.
660 void *oldvalue = node->value;
661 bool oldvalset = node->valset;
662 if (*term == *keyptr)
664 while (*term == *keyptr)
666 /* Find the next free slot in the check array.
667 * This is the "vector base" essentially
669 q = x_check(trie, *term);
671 node = &base[curidx];
672 /* Point the node to the next new base */
674 node->mode = Node_Arc;
675 node->valset = false;
676 /* Advance the input stream and local variables */
678 curidx = q + charval(*term);
679 node = &base[curidx];
680 /* Make sure the new current node has its parent set. */
681 node->parent = lastidx;
682 node->mode = Node_Arc; /* Just in case we run x_check again */
683 *term = '\0'; /* Unmark the string table here */
688 node->valset = false;
690 /* We're done inserting new pairs. If one of them is exhausted,
691 * we take special shortcuts.
693 if (*term == '\0') //EX: BADGERHOUSE added over B -> ADGER.
695 /* First backpatch the current node - it ends the newly split terminator.
696 * In the example, this would mean the node is the production from R -> ?
697 * This node ends the old BADGER, so we set it here.
699 node->valset = oldvalset;
700 node->value = oldvalue;
702 /* The terminator was split up, but pieces of keyptr remain.
703 * We need to generate a new production, in this example, R -> H,
704 * with H being a terminator to OUSE. Thus we get:
705 * B,A,D,G,E,R*,H*->OUSE (* = value set).
706 * NOTE: parent was last set at the end of the while loop.
708 /* Get the new base and apply re-basing */
709 q = x_check(trie, *keyptr);
711 node = &base[curidx];
714 node->mode = Node_Arc;
716 /* Finish the final node */
717 curidx = q + charval(*keyptr);
718 node = &trie->base[curidx];
720 /* Optimize - don't add to string table if there's nothing more to eat */
723 node->mode = Node_Arc;
725 node->idx = x_addstring(trie, keyptr);
726 node->mode = Node_Term;
728 node->parent = lastidx;
731 } else if (*keyptr == '\0') { //EX: BADGER added over B -> ADGERHOUSE
732 /* First backpatch the current node - it ends newly split input string.
733 * This is the exact opposite of the above procedure.
738 /* Get the new base and apply re-basing */
739 q = x_check(trie, *term);
741 node = &base[curidx];
744 node->mode = Node_Arc;
746 /* Finish the final node */
747 curidx = q + charval(*term);
748 node = &trie->base[curidx];
750 /* Optimize - don't add to string table if there's nothing more to eat */
753 node->mode = Node_Arc;
755 node->idx = (term - trie->stringtab); /* Already in the string table! */
756 node->mode = Node_Term;
758 node->parent = lastidx;
759 node->valset = oldvalset;
760 node->value = oldvalue;
762 /* Finally, we have to create two new nodes instead of just one. */
763 node->mode = Node_Arc;
765 /* Get the new base and apply re-basing */
766 q = x_check2(trie, *keyptr, *term);
768 node = &base[curidx];
773 /* Re-create the old terminated node */
774 curidx = q + charval(*term);
775 node = &trie->base[curidx];
777 node->valset = oldvalset;
778 node->value = oldvalue;
779 node->parent = lastidx;
782 node->mode = Node_Arc;
784 node->mode = Node_Term;
785 node->idx = (term - trie->stringtab); /* Already in the string table! */
788 /* Create the new keyed input node */
789 curidx = q + charval(*keyptr);
790 node = &trie->base[curidx];
794 node->parent = lastidx;
797 node->mode = Node_Arc;
799 node->mode = Node_Term;
800 node->idx = x_addstring(trie, keyptr);
807 assert(node->mode == Node_Arc);
811 } while (*keyptr != '\0');
815 /* If we've exhausted the string and we have a valid reached node,
816 * the production rule already existed. Make sure it's valid to set first.
819 /* We have to be an Arc. If the last result was anything else, we would have returned a new
820 * production earlier.
822 assert(node->mode == Node_Arc);
824 if (!node->valset || replace_allowed)
826 /* Insert is only possible if we have no production */
835 bool sm_trie_insert(Trie *trie, const char *key, void *value)
837 return sm_trie_add(trie, key, value, false);
840 bool sm_trie_replace(Trie *trie, const char *key, void *value)
842 return sm_trie_add(trie, key, value, true);