fixed a state bug in the gameconf parser that would break parsing after a signature section was done
3 * ===============================================================
4 * SourceMod (C)2004-2007 AlliedModders LLC. All rights reserved.
5 * ===============================================================
7 * This file is not open source and may not be copied without explicit
8 * written permission of AlliedModders LLC. This file may not be redistributed
9 * in whole or significant part.
10 * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
21 * Double Array Trie algorithm, based on:
22 * An Efficient Implementation of Trie Structures, by
23 * Jun-ichi Aoe and Katsushi Maromoto, and Takashi Sato
24 * from Software - Practice and Experience, Vol. 22(9), 695-721 (September 1992)
26 * A Trie is a simple data structure which stores strings as DFAs, with each
27 * transition state being a string entry. For example, observe the following strings:
29 * BAILOPAN, BAT, BACON, BACK
30 * These transition as the follow production rules:
41 * The standard implementation for this - using lists - gives a slow linear lookup, somewhere between
42 * O(N+M) or O(log n). A faster implementation is proposed in the paper above, which is based on compacting
43 * the transition states into two arrays. In the paper's implementation, two arrays are used, and thus it is
44 * called the "Double Array" algorithm. However, the CHECK array's size is maintained the same as BASE,
45 * so they can be combined into one structure. The array seems complex at first, but is very simple: it is a
46 * tree structure flattened out into a single vector. I am calling this implementation the Flat Array Trie.
48 * BASE[] is an array where each member is a node in the Trie. The node can either be UNUSED (empty), an ARC
49 * (containing an offset to the next set of ARCs), or a TERMINATOR (contains the rest of a string).
50 * Each node has an index which must be interpreted based on the node type. If the node is a TERMINATOR, then the
51 * index is an index into a string table, to find the rest of the string.
52 * If the node is an ARC, the index is another index into BASE. For each possible token that can follow the
53 * current token, the value of those tokens can be added to the index given in the ARC. Thus, given a current
54 * position and the next desired token, the current arc will jump to another arc which can contain either:
55 * 1) An invalid production (collision, no entry exists)
56 * 2) An empty production (no entry exists)
57 * 3) Another arc label (the string ends here or continues into more productions)
58 * 4) A TERMINATOR (the string ends here and contains an unused set of productions)
60 * So, given current offset N (starting at N=1), jumping to token C means the next offset will be:
62 * Thus, the next node will be at:
65 * This allows each ARC to specify the base offset for any of its ARC children, like a tree. Each node specifies
66 * its parent ARC -- so if an invalid offset is specified, the parent will not match, and thus no such derived
69 * This means that arrays can be laid out "sparsely," maximizing their usage. Note that N need not be related to
70 * 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
71 * insertion comes with a small deal of complexity. To insert a new set of tokens T, the algorithm finds a new
72 * BASE index N such that BASE[N+T[i]] is unused for each T[i]. Thus, indirection is not necessarily linear;
73 * traversing a chain of ARC nodes can _and will_ jump around BASE.
75 * Of course, given this level of flexibility in the array organization, there are collisions. This is largely
76 * where insertions become slow, as the old chain must be relocated before the new one is used. Relocation means
77 * finding one or more new base indexes, and this means traversing BASE until an acceptable index is found, such
78 * that each offset is unused (see description in previous paragraph).
80 * However, it is not insertion time we are concerned about. The "trie" name comes from reTRIEval. We are only
81 * concerned with lookup and deletion. Both lookup and deletion are O(k), where k is relative to the length of the
82 * input string. Note that it is best case O(1) and worst case O(k). Deleting the entire trie is always O(1).
86 * Optimization ideas for the future:
87 * 1) Store a reference count for each arc, with the count of sub-children.
88 * This could let us break out of "children searches" for case 4 easily.
89 * 2) Use a 'free list' so we can easily search the trie for free points.
90 * This would drastically speed up x_check*
95 Node_Unused = 0, /* Node is not being used (sparse) */
96 Node_Arc, /* Node is part of an arc and does not terminate */
97 Node_Term, /* Node is a terminator */
103 * For Node_Arc, this index stores the 'base' offset to the next arc chain.
104 * I.e. to jump from this arc to character C, it will be at base[idx+C].
105 * For Node_Term, this is an index into the string table.
110 * This contains the prior arc that we must have come from.
111 * For example, if arc 63 has a base jump of index 12, and we want to see if
112 * there is a valid character C, the parent of 12+C must be 63.
116 void *value; /* Value associated with this node */
117 NodeType mode; /* Current usage type of the node */
118 bool valset; /* Whether or not a value is set */
123 TrieNode *base; /* Base array for the sparse tables */
124 char *stringtab; /* String table pointer */
125 unsigned int baseSize; /* Size of the base array, in members */
126 unsigned int stSize; /* Size of the string table, in bytes */
127 unsigned int tail; /* Current unused offset into the string table */
130 inline unsigned char charval(char c)
132 return (unsigned char)c;
135 bool sm_trie_grow(Trie *trie)
137 /* The current # of nodes in the tree is trie->baseSize + 1 */
138 unsigned int curSize = trie->baseSize;
139 unsigned int newSize = curSize * 2;
141 //:TODO: Make functions calling this return failure if this fails
142 trie->base = (TrieNode *)realloc(trie->base, (newSize + 1) * sizeof(TrieNode));
148 memset(&trie->base[curSize+1], 0, (newSize - curSize) * sizeof(TrieNode));
149 trie->baseSize = newSize;
154 unsigned int x_check(Trie *trie, char c, unsigned int start=1)
156 TrieNode *base = trie->base;
157 unsigned char _c = charval(c);
158 unsigned int to_check = trie->baseSize - _c;
159 for (unsigned int i=start; i<=to_check; i++)
161 if (base[i+_c].mode == Node_Unused)
169 return x_check(trie, c, to_check+1);
172 unsigned int x_check2(Trie *trie, char c1, char c2, unsigned int start=1)
174 TrieNode *base = trie->base;
175 unsigned char _c1 = charval(c1);
176 unsigned char _c2 = charval(c2);
177 unsigned int to_check = trie->baseSize - (_c1 > _c2 ? _c1 : _c2);
178 for (unsigned int i=start; i<=to_check; i++)
180 if (base[i+_c1].mode == Node_Unused
181 && base[i+_c2].mode == Node_Unused)
189 return x_check2(trie, c1, c2, to_check+1);
192 unsigned int x_check_multi(Trie *trie,
193 unsigned int offsets[],
195 unsigned int start=1)
197 TrieNode *base = trie->base;
199 unsigned int to_check = trie->baseSize;
200 unsigned int highest = 0;
202 for (unsigned int i=0; i<count; i++)
204 if (offsets[i] > highest)
206 highest = offsets[i];
212 for (unsigned int i=start; i<=to_check; i++)
215 for (unsigned int j=0; j<count; j++)
217 cur = &base[i+offsets[j]];
218 if (cur->mode != Node_Unused)
232 return x_check_multi(trie, offsets, count, to_check+1);
235 unsigned int x_addstring(Trie *trie, const char *ptr)
237 size_t len = strlen(ptr) + 1;
239 if (trie->tail + len >= trie->stSize)
241 while (trie->tail + len >= trie->stSize)
245 trie->stringtab = (char *)realloc(trie->stringtab, trie->stSize);
248 unsigned int tail = trie->tail;
249 strcpy(&trie->stringtab[tail], ptr);
255 Trie *sm_trie_create()
259 t->base = (TrieNode *)malloc(sizeof(TrieNode) * (256 + 1));
260 t->stringtab = (char *)malloc(sizeof(char) * 256);
269 void sm_trie_clear(Trie *trie)
273 memset(trie->base, 0, sizeof(TrieNode) * (trie->baseSize + 1));
274 memset(trie->stringtab, 0, sizeof(char) * trie->stSize);
276 /* Sentinel root node */
277 trie->base[1].idx = 1;
278 trie->base[1].mode = Node_Arc;
279 trie->base[1].parent = 1;
282 void sm_trie_destroy(Trie *trie)
285 free(trie->stringtab);
289 bool sm_trie_delete(Trie *trie, const char *key)
291 unsigned int lastidx = 1; /* the last node index */
292 unsigned int curidx; /* current node index */
293 const char *keyptr = key; /* input stream at current token */
294 TrieNode *node = NULL; /* current node being processed */
295 TrieNode *base = trie->base;
302 /* Start traversing at the root node */
305 /* Find where the next character is, then advance */
306 curidx = base[lastidx].idx;
307 node = &base[curidx];
308 curidx += charval(*keyptr);
309 node = &base[curidx];
312 /* Check if this slot is supposed to be empty or is a collision */
313 if ((curidx > trie->baseSize) || node->mode == Node_Unused || node->parent != lastidx)
316 } else if (node->mode == Node_Term) {
317 char *term = &trie->stringtab[node->idx];
318 if (strcmp(keyptr, term) == 0)
324 } while (*keyptr != '\0');
326 assert(node != NULL);
333 node->valset = false;
339 bool sm_trie_retrieve(Trie *trie, const char *key, void **value)
341 unsigned int lastidx = 1; /* the last node index */
342 unsigned int curidx; /* current node index */
343 const char *keyptr = key; /* input stream at current token */
344 TrieNode *node = NULL; /* current node being processed */
345 TrieNode *base = trie->base;
352 /* Start traversing at the root node */
355 /* Find where the next character is, then advance */
356 curidx = base[lastidx].idx;
357 node = &base[curidx];
358 curidx += charval(*keyptr);
359 node = &base[curidx];
362 /* Check if this slot is supposed to be empty or is a collision */
363 if ((curidx > trie->baseSize) || node->mode == Node_Unused || node->parent != lastidx)
366 } else if (node->mode == Node_Term) {
367 char *term = &trie->stringtab[node->idx];
368 if (strcmp(keyptr, term) == 0)
374 } while (*keyptr != '\0');
376 assert(node != NULL);
385 *value = node->value;
391 bool sm_trie_insert(Trie *trie, const char *key, void *value)
393 unsigned int lastidx = 1; /* the last node index */
394 unsigned int curidx; /* current node index */
395 const char *keyptr = key; /* input stream at current token */
396 TrieNode *node = NULL; /* current node being processed */
397 TrieNode *basenode = NULL; /* current base node being processed */
398 unsigned int q; /* temporary var for x_check results */
399 TrieNode *base = trie->base;
400 unsigned int curoffs; /* current offset */
402 /* Do not handle empty strings for simplicity */
408 /* Start traversing at the root node (1) */
411 /* Find where the next character is, then advance */
412 curidx = base[lastidx].idx;
413 basenode = &base[curidx];
414 curoffs = charval(*keyptr);
416 node = &base[curidx];
419 /* Check if this slot is supposed to be empty. If so, we need to handle CASES 1/2:
420 * Insertion without collisions
422 if ( (curidx > trie->baseSize) || (node->mode == Node_Unused) )
424 if (curidx > trie->baseSize)
426 if (!sm_trie_grow(trie))
430 node = &trie->base[curidx];
432 node->parent = lastidx;
435 node->mode = Node_Arc;
437 node->idx = x_addstring(trie, keyptr);
438 node->mode = Node_Term;
444 } else if (node->parent != lastidx) {
445 /* Collision! We have to split up the tree here. CASE 4:
446 * Insertion when a new word is inserted with a collision.
447 * NOTE: This is the hardest case to handle. All below examples are based on:
448 * BACHELOR, BADGE, inserting BABY.
449 * The problematic production here is A -> B, where B is already being used.
451 * This process has to rotate one half of the 'A' arc. We generate two lists:
452 * Outgoing Arcs - Anything leaving this 'A'
453 * Incoming Arcs - Anything going to this 'A'
454 * Whichever list is smaller will be moved. Note that this works because the intersection
455 * affects both arc chains, and moving one will make the slot available to either.
459 /* Find every node arcing from the last node.
460 * I.e. for BACHELOR, BADGE, BABY,
461 * The arcs leaving A will be C and D, but our current node is B -> *.
462 * Thus, we use the last index (A) to find the base for arcs leaving A.
464 unsigned int outgoing_base = base[lastidx].idx;
465 unsigned int outgoing_list[256];
466 unsigned int outgoing_count = 0; /* count the current index here */
467 cur = &base[outgoing_base] + 1;
468 unsigned int outgoing_limit = 255;
470 if (outgoing_base + outgoing_limit > trie->baseSize)
472 outgoing_limit = trie->baseSize - outgoing_base;
475 for (unsigned int i=1; i<=outgoing_limit; i++,cur++)
477 if (cur->mode == Node_Unused || cur->parent != lastidx)
481 outgoing_list[outgoing_count++] = i;
483 outgoing_list[outgoing_count++] = curidx - outgoing_base;
485 /* Now we need to find all the arcs leaving our parent...
486 * Note: the inconsistency is the base of our parent.
488 assert(base[node->parent].mode == Node_Arc);
489 unsigned int incoming_list[256];
490 unsigned int incoming_base = base[node->parent].idx;
491 unsigned int incoming_count = 0;
492 unsigned int incoming_limit = 255;
493 cur = &base[incoming_base] + 1;
495 if (incoming_base + incoming_limit > trie->baseSize)
497 incoming_limit = trie->baseSize - incoming_base;
500 assert(incoming_limit > 0 && incoming_limit <= 255);
502 for (unsigned int i=1; i<=255; i++,cur++)
504 if (cur->mode == Node_Arc || cur->mode == Node_Term)
506 if (cur->parent == node->parent)
508 incoming_list[incoming_count++] = i;
513 if (incoming_count < outgoing_count + 1)
515 unsigned int q = x_check_multi(trie, incoming_list, incoming_count);
518 node = &base[curidx];
520 /* If we're incoming, we need to modify our parent */
521 base[node->parent].idx = q;
523 /* For each node in the "to move" list,
524 * Relocate the node's info to the new position.
526 unsigned int idx, newidx, oldidx;
527 for (unsigned int i=0; i<incoming_count; i++)
529 idx = incoming_list[i];
531 oldidx = incoming_base + idx;
532 if (oldidx == lastidx)
534 /* Important! Make sure we're not invalidating our sacred lastidx */
537 base[newidx] = base[oldidx];
538 assert(base[base[newidx].parent].mode == Node_Arc);
539 memset(&base[oldidx], 0, sizeof(TrieNode));
540 /* If we are not a terminator, we have children we must take care of */
541 if (base[newidx].mode == Node_Arc)
543 TrieNode *check_base = &base[base[newidx].idx] + 1;
544 for (unsigned int j=1; j<=255; j++, check_base++)
546 if (check_base->parent == oldidx)
548 check_base->parent = newidx;
554 unsigned int q = x_check_multi(trie, outgoing_list, outgoing_count);
557 node = &base[curidx];
559 /* If we're outgoing, we need to modify our own base */
560 base[lastidx].idx = q;
562 /* Take the last index (curidx) out of the list. Technically we are not moving this,
563 * since it's already being used by something else.
567 /* For each node in the "to move" list,
568 * Relocate the node's info to the new position.
570 unsigned int idx, newidx, oldidx;
571 for (unsigned int i=0; i<outgoing_count; i++)
573 idx = outgoing_list[i];
575 oldidx = outgoing_base + idx;
576 if (oldidx == lastidx)
578 /* Important! Make sure we're not invalidating our sacred lastidx */
581 base[newidx] = base[oldidx];
582 assert(base[base[newidx].parent].mode == Node_Arc);
583 memset(&base[oldidx], 0, sizeof(TrieNode));
584 /* If we are not a terminator, we have children we must take care of */
585 if (base[newidx].mode == Node_Arc)
587 TrieNode *check_base = &base[base[newidx].idx] + 1;
588 for (unsigned int j=1; j<=255; j++, check_base++)
590 if (check_base->parent == oldidx)
592 check_base->parent = newidx;
598 /* Take the invisible node and use it as our new node */
599 node = &base[q + outgoing_list[outgoing_count]];
602 /* We're finally done! */
603 node->parent = lastidx;
606 node->mode = Node_Arc;
608 node->idx = x_addstring(trie, keyptr);
609 node->mode = Node_Term;
616 /* See what's in the next node - special case if terminator! */
617 if (node->mode == Node_Term)
619 /* If we're a terminator, we need to handle CASE 3:
620 * Insertion when a terminating collision occurs
622 char *term = &trie->stringtab[node->idx];
623 /* Do an initial browsing to make sure they're not the same string */
624 if (strcmp(keyptr, term) == 0)
632 /* Same string. We can't insert. */
635 /* For each matching character pair, we need to disband the terminator.
636 * This splits the similar prefix into a single arc path.
637 * First, save the old values so we can move them to a new node.
638 * Next, for each loop:
639 * Take the current (invalid) node, and point it to the next arc base.
640 * Set the current node to the node at the next arc.
642 void *oldvalue = node->value;
643 bool oldvalset = node->valset;
644 if (*term == *keyptr)
646 while (*term == *keyptr)
648 /* Find the next free slot in the check array.
649 * This is the "vector base" essentially
651 q = x_check(trie, *term);
653 node = &base[curidx];
654 /* Point the node to the next new base */
656 node->mode = Node_Arc;
657 node->valset = false;
658 /* Advance the input stream and local variables */
660 curidx = q + charval(*term);
661 node = &base[curidx];
662 /* Make sure the new current node has its parent set. */
663 node->parent = lastidx;
664 node->mode = Node_Arc; /* Just in case we run x_check again */
665 *term = '\0'; /* Unmark the string table here */
670 node->valset = false;
672 /* We're done inserting new pairs. If one of them is exhausted,
673 * we take special shortcuts.
675 if (*term == '\0') //EX: BADGERHOUSE added over B -> ADGER.
677 /* First backpatch the current node - it ends the newly split terminator.
678 * In the example, this would mean the node is the production from R -> ?
679 * This node ends the old BADGER, so we set it here.
681 node->valset = oldvalset;
682 node->value = oldvalue;
684 /* The terminator was split up, but pieces of keyptr remain.
685 * We need to generate a new production, in this example, R -> H,
686 * with H being a terminator to OUSE. Thus we get:
687 * B,A,D,G,E,R*,H*->OUSE (* = value set).
688 * NOTE: parent was last set at the end of the while loop.
690 /* Get the new base and apply re-basing */
691 q = x_check(trie, *keyptr);
693 node = &base[curidx];
696 node->mode = Node_Arc;
698 /* Finish the final node */
699 curidx = q + charval(*keyptr);
700 node = &trie->base[curidx];
702 /* Optimize - don't add to string table if there's nothing more to eat */
705 node->mode = Node_Arc;
707 node->idx = x_addstring(trie, keyptr);
708 node->mode = Node_Term;
710 node->parent = lastidx;
713 } else if (*keyptr == '\0') { //EX: BADGER added over B -> ADGERHOUSE
714 /* First backpatch the current node - it ends newly split input string.
715 * This is the exact opposite of the above procedure.
720 /* Get the new base and apply re-basing */
721 q = x_check(trie, *term);
723 node = &base[curidx];
726 node->mode = Node_Arc;
728 /* Finish the final node */
729 curidx = q + charval(*term);
730 node = &trie->base[curidx];
732 /* Optimize - don't add to string table if there's nothing more to eat */
735 node->mode = Node_Arc;
737 node->idx = (term - trie->stringtab); /* Already in the string table! */
738 node->mode = Node_Term;
740 node->parent = lastidx;
741 node->valset = oldvalset;
742 node->value = oldvalue;
744 /* Finally, we have to create two new nodes instead of just one. */
745 node->mode = Node_Arc;
747 /* Get the new base and apply re-basing */
748 q = x_check2(trie, *keyptr, *term);
750 node = &base[curidx];
755 /* Re-create the old terminated node */
756 curidx = q + charval(*term);
757 node = &trie->base[curidx];
759 node->valset = oldvalset;
760 node->value = oldvalue;
761 node->parent = lastidx;
764 node->mode = Node_Arc;
766 node->mode = Node_Term;
767 node->idx = (term - trie->stringtab); /* Already in the string table! */
770 /* Create the new keyed input node */
771 curidx = q + charval(*keyptr);
772 node = &trie->base[curidx];
776 node->parent = lastidx;
779 node->mode = Node_Arc;
781 node->mode = Node_Term;
782 node->idx = x_addstring(trie, keyptr);
789 assert(node->mode == Node_Arc);
793 } while (*keyptr != '\0');
797 /* If we've exhausted the string and we have a valid reached node,
798 * the production rule already existed. Make sure it's valid to set first.
801 /* We have to be an Arc. If the last result was anything else, we would have returned a new
802 * production earlier.
804 assert(node->mode == Node_Arc);
808 /* Insert is only possible if we have no production */