added experimental extension interface for loading external extensions from mm:s
hard-bumped the extension api
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>.
32 #ifndef _INCLUDE_SOURCEMOD_TEMPLATED_TRIE_H_
33 #define _INCLUDE_SOURCEMOD_TEMPLATED_TRIE_H_
42 Node_Unused = 0, /* Node is not being used (sparse) */
43 Node_Arc, /* Node is part of an arc and does not terminate */
44 Node_Term, /* Node is a terminator */
48 * @brief Trie class for storing key/value pairs, based on double array tries.
51 * For full works cited and implementation overview, there is a big comment
52 * block at the bottom of this file.
61 * @brief Clears all set objects in the trie.
70 * @brief Removes a key from the trie.
72 * @param key Key to remove.
73 * @return True on success, false if key was never set.
75 bool remove(const char *key)
77 KTrieNode *node = internal_retrieve(key);
78 if (!node || !node->valset)
90 * @brief Retrieves a pointer to the object stored at a given key.
92 * @param key Key to retrieve.
93 * @return Pointer to object, or NULL if key was not found or not set.
95 K * retrieve(const char *key)
97 KTrieNode *node = internal_retrieve(key);
98 if (!node || !node->valset)
106 * @brief Inserts or updates the object stored at a key.
108 * @param key Key to update or insert.
109 * @param obj Object to store at the key.
110 * @return True on success, false on failure.
112 bool replace(const char *key, const K & obj)
114 KTrieNode *prev_node = internal_retrieve(key);
117 return insert(key, obj);
120 if (prev_node->valset)
122 prev_node->value.~K();
125 new (&prev_node->value) K(obj);
131 * @brief Inserts an object at a key.
133 * @param key Key to insert at.
134 * @param obj Object to store at the key.
135 * @return True on success, false if the key is already set or
136 * insertion otherwise failed.
138 bool insert(const char *key, const K & obj)
140 unsigned int lastidx = 1; /* the last node index */
141 unsigned int curidx; /* current node index */
142 const char *keyptr = key; /* input stream at current token */
143 KTrieNode *node = NULL; /* current node being processed */
144 KTrieNode *basenode = NULL; /* current base node being processed */
145 unsigned int q; /* temporary var for x_check results */
146 unsigned int curoffs; /* current offset */
148 /* Do not handle empty strings for simplicity */
154 /* Start traversing at the root node (1) */
157 /* Find where the next character is, then advance */
158 curidx = m_base[lastidx].idx;
159 basenode = &m_base[curidx];
160 curoffs = charval(*keyptr);
162 node = &m_base[curidx];
165 /* Check if this slot is supposed to be empty. If so, we need to handle CASES 1/2:
166 * Insertion without collisions
168 if ( (curidx > m_baseSize) || (node->mode == Node_Unused) )
170 if (curidx > m_baseSize)
176 node = &m_base[curidx];
178 node->parent = lastidx;
181 node->mode = Node_Arc;
185 node->idx = x_addstring(keyptr);
186 node->mode = Node_Term;
189 new (&node->value) K(obj);
193 else if (node->parent != lastidx)
195 /* Collision! We have to split up the tree here. CASE 4:
196 * Insertion when a new word is inserted with a collision.
197 * NOTE: This is the hardest case to handle. All below examples are based on:
198 * BACHELOR, BADGE, inserting BABY.
199 * The problematic production here is A -> B, where B is already being used.
201 * This process has to rotate one half of the 'A' arc. We generate two lists:
202 * Outgoing Arcs - Anything leaving this 'A'
203 * Incoming Arcs - Anything going to this 'A'
204 * Whichever list is smaller will be moved. Note that this works because the intersection
205 * affects both arc chains, and moving one will make the slot available to either.
209 /* Find every node arcing from the last node.
210 * I.e. for BACHELOR, BADGE, BABY,
211 * The arcs leaving A will be C and D, but our current node is B -> *.
212 * Thus, we use the last index (A) to find the base for arcs leaving A.
214 unsigned int outgoing_base = m_base[lastidx].idx;
215 unsigned int outgoing_list[256];
216 unsigned int outgoing_count = 0; /* count the current index here */
217 cur = &m_base[outgoing_base] + 1;
218 unsigned int outgoing_limit = 255;
220 if (outgoing_base + outgoing_limit > m_baseSize)
222 outgoing_limit = m_baseSize - outgoing_base;
225 for (unsigned int i=1; i<=outgoing_limit; i++,cur++)
227 if (cur->mode == Node_Unused || cur->parent != lastidx)
231 outgoing_list[outgoing_count++] = i;
233 outgoing_list[outgoing_count++] = curidx - outgoing_base;
235 /* Now we need to find all the arcs leaving our parent...
236 * Note: the inconsistency is the base of our parent.
238 assert(m_base[node->parent].mode == Node_Arc);
239 unsigned int incoming_list[256];
240 unsigned int incoming_base = m_base[node->parent].idx;
241 unsigned int incoming_count = 0;
242 unsigned int incoming_limit = 255;
243 cur = &m_base[incoming_base] + 1;
245 if (incoming_base + incoming_limit > m_baseSize)
247 incoming_limit = m_baseSize - incoming_base;
250 assert(incoming_limit > 0 && incoming_limit <= 255);
252 for (unsigned int i=1; i<=incoming_limit; i++,cur++)
254 if (cur->mode == Node_Arc || cur->mode == Node_Term)
256 if (cur->parent == node->parent)
258 incoming_list[incoming_count++] = i;
263 if (incoming_count < outgoing_count + 1)
265 unsigned int q = x_check_multi(incoming_list, incoming_count);
267 node = &m_base[curidx];
269 /* If we're incoming, we need to modify our parent */
270 m_base[node->parent].idx = q;
272 /* For each node in the "to move" list,
273 * Relocate the node's info to the new position.
275 unsigned int idx, newidx, oldidx;
276 for (unsigned int i=0; i<incoming_count; i++)
278 idx = incoming_list[i];
280 oldidx = incoming_base + idx;
281 if (oldidx == lastidx)
283 /* Important! Make sure we're not invalidating our sacred lastidx */
286 /* Fully copy the node */
287 memcpy(&m_base[newidx], &m_base[oldidx], sizeof(KTrieNode));
288 if (m_base[oldidx].valset)
290 new (&m_base[newidx].value) K(m_base[oldidx].value);
291 m_base[oldidx].value.~K();
293 assert(m_base[m_base[newidx].parent].mode == Node_Arc);
295 memset(&m_base[oldidx], 0, sizeof(KTrieNode));
296 /* If we are not a terminator, we have children we must take care of */
297 if (m_base[newidx].mode == Node_Arc)
299 KTrieNode *check_base = &m_base[m_base[newidx].idx] + 1;
300 outgoing_limit = (m_base + m_baseSize + 1) - check_base;
301 if (outgoing_limit > 255)
303 outgoing_limit = 255;
305 for (unsigned int j=1; j<=outgoing_limit; j++, check_base++)
307 if (check_base->parent == oldidx)
309 check_base->parent = newidx;
317 unsigned int q = x_check_multi(outgoing_list, outgoing_count);
319 node = &m_base[curidx];
321 /* If we're outgoing, we need to modify our own base */
322 m_base[lastidx].idx = q;
324 /* Take the last index (curidx) out of the list. Technically we are not moving this,
325 * since it's already being used by something else.
329 /* For each node in the "to move" list,
330 * Relocate the node's info to the new position.
332 unsigned int idx, newidx, oldidx;
333 for (unsigned int i=0; i<outgoing_count; i++)
335 idx = outgoing_list[i];
337 oldidx = outgoing_base + idx;
338 if (oldidx == lastidx)
340 /* Important! Make sure we're not invalidating our sacred lastidx */
343 /* Fully copy the node */
344 memcpy(&m_base[newidx], &m_base[oldidx], sizeof(KTrieNode));
345 if (m_base[oldidx].valset)
347 new (&m_base[newidx].value) K(m_base[oldidx].value);
348 m_base[oldidx].value.~K();
350 assert(m_base[m_base[newidx].parent].mode == Node_Arc);
352 memset(&m_base[oldidx], 0, sizeof(KTrieNode));
353 /* If we are not a terminator, we have children we must take care of */
354 if (m_base[newidx].mode == Node_Arc)
356 KTrieNode *check_base = &m_base[m_base[newidx].idx] + 1;
357 outgoing_limit = (m_base + m_baseSize + 1) - check_base;
358 if (outgoing_limit > 255)
360 outgoing_limit = 255;
362 for (unsigned int j=1; j<=outgoing_limit; j++, check_base++)
364 if (check_base->parent == oldidx)
366 check_base->parent = newidx;
372 /* Take the invisible node and use it as our new node */
373 node = &m_base[q + outgoing_list[outgoing_count]];
376 /* We're finally done! */
377 node->parent = lastidx;
380 node->mode = Node_Arc;
384 node->idx = x_addstring(keyptr);
385 node->mode = Node_Term;
388 new (&node->value) K(obj);
394 /* See what's in the next node - special case if terminator! */
395 if (node->mode == Node_Term)
397 /* If we're a terminator, we need to handle CASE 3:
398 * Insertion when a terminating collision occurs
400 char *term = &m_stringtab[node->idx];
401 /* Do an initial browsing to make sure they're not the same string */
402 if (strcmp(keyptr, term) == 0)
407 new (&node->value) K(obj);
410 /* Same string. We can't insert. */
413 /* For each matching character pair, we need to disband the terminator.
414 * This splits the similar prefix into a single arc path.
415 * First, save the old values so we can move them to a new node.
416 * Next, for each loop:
417 * Take the current (invalid) node, and point it to the next arc base.
418 * Set the current node to the node at the next arc.
421 bool oldvalset = node->valset;
424 oldvalue = node->value;
426 if (*term == *keyptr)
428 while (*term == *keyptr)
430 /* Find the next free slot in the check array.
431 * This is the "vector base" essentially
434 node = &m_base[curidx];
435 /* Point the node to the next new base */
437 node->mode = Node_Arc;
438 if (node->valset == true)
441 node->valset = false;
443 /* Advance the input stream and local variables */
445 curidx = q + charval(*term);
446 node = &m_base[curidx];
447 /* Make sure the new current node has its parent set. */
448 node->parent = lastidx;
449 node->mode = Node_Arc; /* Just in case we run x_check again */
450 *term = '\0'; /* Unmark the string table here */
455 else if (node->valset)
457 node->valset = false;
460 /* We're done inserting new pairs. If one of them is exhausted,
461 * we take special shortcuts.
463 if (*term == '\0') //EX: BADGERHOUSE added over B -> ADGER.
465 /* First backpatch the current node - it ends the newly split terminator.
466 * In the example, this would mean the node is the production from R -> ?
467 * This node ends the old BADGER, so we set it here.
469 node->valset = oldvalset;
472 new (&node->value) K(oldvalue);
475 /* The terminator was split up, but pieces of keyptr remain.
476 * We need to generate a new production, in this example, R -> H,
477 * with H being a terminator to OUSE. Thus we get:
478 * B,A,D,G,E,R*,H*->OUSE (* = value set).
479 * NOTE: parent was last set at the end of the while loop.
481 /* Get the new base and apply re-basing */
482 q = x_check(*keyptr);
483 node = &m_base[curidx];
486 node->mode = Node_Arc;
488 /* Finish the final node */
489 curidx = q + charval(*keyptr);
490 node = &m_base[curidx];
492 /* Optimize - don't add to string table if there's nothing more to eat */
495 node->mode = Node_Arc;
499 node->idx = x_addstring(keyptr);
500 node->mode = Node_Term;
502 node->parent = lastidx;
504 new (&node->value) K(obj);
506 else if (*keyptr == '\0')
507 { //EX: BADGER added over B -> ADGERHOUSE
508 /* First backpatch the current node - it ends newly split input string.
509 * This is the exact opposite of the above procedure.
512 new (&node->value) K(obj);
514 /* Get the new base and apply re-basing */
516 node = &m_base[curidx];
519 node->mode = Node_Arc;
521 /* Finish the final node */
522 curidx = q + charval(*term);
523 node = &m_base[curidx];
525 /* Optimize - don't add to string table if there's nothing more to eat */
528 node->mode = Node_Arc;
532 node->idx = (term - m_stringtab); /* Already in the string table! */
533 node->mode = Node_Term;
535 node->parent = lastidx;
536 node->valset = oldvalset;
539 new (&node->value) K(oldvalue);
544 /* Finally, we have to create two new nodes instead of just one. */
545 node->mode = Node_Arc;
547 /* Get the new base and apply re-basing */
548 q = x_check2(*keyptr, *term);
549 node = &m_base[curidx];
554 /* Re-create the old terminated node */
555 curidx = q + charval(*term);
556 node = &m_base[curidx];
558 node->valset = oldvalset;
561 new (&node->value) K(oldvalue);
563 node->parent = lastidx;
566 node->mode = Node_Arc;
570 node->mode = Node_Term;
571 node->idx = (term - m_stringtab); /* Already in the string table! */
574 /* Create the new keyed input node */
575 curidx = q + charval(*keyptr);
576 node = &m_base[curidx];
579 new (&node->value) K(obj);
580 node->parent = lastidx;
583 node->mode = Node_Arc;
587 node->mode = Node_Term;
588 node->idx = x_addstring(keyptr);
597 assert(node->mode == Node_Arc);
601 } while (*keyptr != '\0');
605 /* If we've exhausted the string and we have a valid reached node,
606 * the production rule already existed. Make sure it's valid to set first.
609 /* We have to be an Arc. If the last result was anything else, we would have returned a new
610 * production earlier.
612 assert(node->mode == Node_Arc);
617 new (&node->value) K(obj);
626 m_base = (KTrieNode *)malloc(sizeof(KTrieNode) * (256 + 1));
627 m_stringtab = (char *)malloc(sizeof(char) * 256);
645 * For Node_Arc, this index stores the 'base' offset to the next arc chain.
646 * I.e. to jump from this arc to character C, it will be at base[idx+C].
647 * For Node_Term, this is an index into the string table.
652 * This contains the prior arc that we must have come from.
653 * For example, if arc 63 has a base jump of index 12, and we want to see if
654 * there is a valid character C, the parent of 12+C must be 63.
657 K value; /* Value associated with this node */
658 NodeType mode; /* Current usage type of the node */
659 bool valset; /* Whether or not a value is set */
662 KTrieNode *internal_retrieve(const char *key)
664 unsigned int lastidx = 1; /* the last node index */
665 unsigned int curidx; /* current node index */
666 const char *keyptr = key; /* input stream at current token */
667 KTrieNode *node = NULL; /* current node being processed */
674 /* Start traversing at the root node */
677 /* Find where the next character is, then advance */
678 curidx = m_base[lastidx].idx;
679 node = &m_base[curidx];
680 curidx += charval(*keyptr);
681 node = &m_base[curidx];
684 /* Check if this slot is supposed to be empty or is a collision */
685 if ((curidx > m_baseSize) || node->mode == Node_Unused || node->parent != lastidx)
689 else if (node->mode == Node_Term)
691 char *term = &m_stringtab[node->idx];
692 if (strcmp(keyptr, term) == 0)
702 } while (*keyptr != '\0');
708 /* The current # of nodes in the tree is trie->baseSize + 1 */
709 unsigned int cur_size = m_baseSize;
710 unsigned int new_size = cur_size * 2;
712 KTrieNode *new_base = (KTrieNode *)malloc((new_size + 1) * sizeof(KTrieNode));
718 memcpy(new_base, m_base, sizeof(KTrieNode) * (m_baseSize + 1));
719 memset(&new_base[cur_size + 1], 0, (new_size - cur_size) * sizeof(KTrieNode));
721 for (size_t i = 0; i <= m_baseSize; i++)
723 if (m_base[i].valset)
725 /* Placement construct+copy the object, then placement destroy the old. */
726 new (&new_base[i].value) K(m_base[i].value);
727 m_base[i].value.~K();
733 m_baseSize = new_size;
737 inline unsigned char charval(char c)
739 return (unsigned char)c;
741 void internal_clear()
745 memset(m_base, 0, sizeof(KTrieNode) * (m_baseSize + 1));
746 memset(m_stringtab, 0, sizeof(char) * m_stSize);
748 /* Sentinel root node */
750 m_base[1].mode = Node_Arc;
751 m_base[1].parent = 1;
753 void run_destructors()
755 for (size_t i = 0; i <= m_baseSize; i++)
757 if (m_base[i].valset)
759 m_base[i].value.~K();
763 unsigned int x_addstring(const char *ptr)
765 size_t len = strlen(ptr) + 1;
767 if (m_tail + len >= m_stSize)
769 while (m_tail + len >= m_stSize)
773 m_stringtab = (char *)realloc(m_stringtab,m_stSize);
776 unsigned int tail = m_tail;
777 strcpy(&m_stringtab[tail], ptr);
782 unsigned int x_check(char c, unsigned int start=1)
784 unsigned char _c = charval(c);
785 unsigned int to_check = m_baseSize - _c;
786 for (unsigned int i=start; i<=to_check; i++)
788 if (m_base[i+_c].mode == Node_Unused)
796 return x_check(c, to_check+1);
798 unsigned int x_check2(char c1, char c2, unsigned int start=1)
800 unsigned char _c1 = charval(c1);
801 unsigned char _c2 = charval(c2);
802 unsigned int to_check = m_baseSize - (_c1 > _c2 ? _c1 : _c2);
803 for (unsigned int i=start; i<=to_check; i++)
805 if (m_base[i+_c1].mode == Node_Unused
806 && m_base[i+_c2].mode == Node_Unused)
814 return x_check2(c1, c2, to_check+1);
816 unsigned int x_check_multi(
817 unsigned int offsets[],
819 unsigned int start=1)
822 unsigned int to_check = m_baseSize;
823 unsigned int highest = 0;
825 for (unsigned int i=0; i<count; i++)
827 if (offsets[i] > highest)
829 highest = offsets[i];
835 for (unsigned int i=start; i<=to_check; i++)
838 for (unsigned int j=0; j<count; j++)
840 cur = &m_base[i+offsets[j]];
841 if (cur->mode != Node_Unused)
855 return x_check_multi(offsets, count, to_check+1);
858 KTrieNode *m_base; /* Base array for the sparse tables */
859 char *m_stringtab; /* String table pointer */
860 unsigned int m_baseSize; /* Size of the base array, in members */
861 unsigned int m_stSize; /* Size of the string table, in bytes */
862 unsigned int m_tail; /* Current unused offset into the string table */
866 * Double Array Trie algorithm, based on:
867 * An Efficient Implementation of Trie Structures, by
868 * Jun-ichi Aoe and Katsushi Maromoto, and Takashi Sato
869 * from Software - Practice and Experience, Vol. 22(9), 695-721 (September 1992)
871 * A Trie is a simple data structure which stores strings as DFAs, with each
872 * transition state being a string entry. For example, observe the following strings:
874 * BAILOPAN, BAT, BACON, BACK
875 * These transition as the follow production rules:
886 * The standard implementation for this - using lists - gives a slow linear lookup, somewhere between
887 * O(N+M) or O(log n). A faster implementation is proposed in the paper above, which is based on compacting
888 * the transition states into two arrays. In the paper's implementation, two arrays are used, and thus it is
889 * called the "Double Array" algorithm. However, the CHECK array's size is maintained the same as BASE,
890 * so they can be combined into one structure. The array seems complex at first, but is very simple: it is a
891 * tree structure flattened out into a single vector. I am calling this implementation the Flat Array Trie.
893 * BASE[] is an array where each member is a node in the Trie. The node can either be UNUSED (empty), an ARC
894 * (containing an offset to the next set of ARCs), or a TERMINATOR (contains the rest of a string).
895 * Each node has an index which must be interpreted based on the node type. If the node is a TERMINATOR, then the
896 * index is an index into a string table, to find the rest of the string.
897 * If the node is an ARC, the index is another index into BASE. For each possible token that can follow the
898 * current token, the value of those tokens can be added to the index given in the ARC. Thus, given a current
899 * position and the next desired token, the current arc will jump to another arc which can contain either:
900 * 1) An invalid production (collision, no entry exists)
901 * 2) An empty production (no entry exists)
902 * 3) Another arc label (the string ends here or continues into more productions)
903 * 4) A TERMINATOR (the string ends here and contains an unused set of productions)
905 * So, given current offset N (starting at N=1), jumping to token C means the next offset will be:
907 * Thus, the next node will be at:
910 * This allows each ARC to specify the base offset for any of its ARC children, like a tree. Each node specifies
911 * its parent ARC -- so if an invalid offset is specified, the parent will not match, and thus no such derived
914 * This means that arrays can be laid out "sparsely," maximizing their usage. Note that N need not be related to
915 * 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
916 * insertion comes with a small deal of complexity. To insert a new set of tokens T, the algorithm finds a new
917 * BASE index N such that BASE[N+T[i]] is unused for each T[i]. Thus, indirection is not necessarily linear;
918 * traversing a chain of ARC nodes can _and will_ jump around BASE.
920 * Of course, given this level of flexibility in the array organization, there are collisions. This is largely
921 * where insertions become slow, as the old chain must be relocated before the new one is used. Relocation means
922 * finding one or more new base indexes, and this means traversing BASE until an acceptable index is found, such
923 * that each offset is unused (see description in previous paragraph).
925 * However, it is not insertion time we are concerned about. The "trie" name comes from reTRIEval. We are only
926 * concerned with lookup and deletion. Both lookup and deletion are O(k), where k is relative to the length of the
927 * input string. Note that it is best case O(1) and worst case O(k). Deleting the entire trie is always O(1).
930 #endif //_INCLUDE_SOURCEMOD_TEMPLATED_TRIE_H_