core/sm_trie.cpp
author David Anderson <dvander@alliedmods.net>
Sun Aug 19 18:34:36 2007 +0000 (2007-08-19)
changeset 1361 591f6d2fd11d
parent 1330 ab94316bb52b
child 1362 a07d745d1b3c
permissions -rw-r--r--
added helper function for panel text
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2007 AlliedModders LLC.  All rights reserved.
     6  * =============================================================================
     7  *
     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.
    11  * 
    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
    15  * details.
    16  *
    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/>.
    19  *
    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>.
    28  *
    29  * Version: $Id$
    30  */
    31 
    32 #include <string.h>
    33 #include <stdlib.h>
    34 #include <assert.h>
    35 #include "sm_trie.h"
    36 
    37 /**
    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)
    42  *
    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:
    45  *
    46  * BAILOPAN, BAT, BACON, BACK
    47  *  These transition as the follow production rules:
    48  *  B -> ...                  B
    49  *       A -> ...             BA
    50  *            I -> ...        BAI
    51  *                 LOPAN      BAILOPAN
    52  *            T -> ...        BAT
    53  *            C ->            BAC
    54  *                 O -> ...   BACO
    55  *                      N     BACON
    56  *                 K          BACK
    57  *
    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.
    64  *
    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)
    76  * 
    77  *  So, given current offset N (starting at N=1), jumping to token C means the next offset will be:
    78  *      offs = BASE[n] + C
    79  *  Thus, the next node will be at:
    80  *      BASE[BASE[n] + C]
    81  * 
    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 
    84  * string exists.
    85  *
    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.
    91  *
    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).
    96  *
    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).
   100  */
   101 
   102 /**
   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*
   108  */
   109 
   110 enum NodeType
   111 {
   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 */
   115 };
   116 
   117 struct TrieNode
   118 {
   119 	/**
   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.
   123 	 */
   124 	unsigned int idx;
   125 
   126 	/**
   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.
   130 	 */
   131 	unsigned int parent;
   132 
   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 */
   136 };
   137 
   138 struct Trie
   139 {
   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 */
   145 };
   146 
   147 inline unsigned char charval(char c)
   148 {
   149 	return (unsigned char)c;
   150 }
   151 
   152 bool sm_trie_grow(Trie *trie)
   153 {
   154 	/* The current # of nodes in the tree is trie->baseSize + 1 */
   155 	unsigned int curSize = trie->baseSize;
   156 	unsigned int newSize = curSize * 2;
   157 
   158 	//:TODO: Make functions calling this return failure if this fails 
   159 	trie->base = (TrieNode *)realloc(trie->base, (newSize + 1) * sizeof(TrieNode));
   160 	if (!trie->base)
   161 	{
   162 		return false;
   163 	}
   164 
   165 	memset(&trie->base[curSize+1], 0, (newSize - curSize) * sizeof(TrieNode));
   166 	trie->baseSize = newSize;
   167 
   168 	return true;
   169 }
   170 
   171 unsigned int x_check(Trie *trie, char c, unsigned int start=1)
   172 {
   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++)
   177 	{
   178 		if (base[i+_c].mode == Node_Unused)
   179 		{
   180 			return i;
   181 		}
   182 	}
   183 
   184 	sm_trie_grow(trie);
   185 
   186 	return x_check(trie, c, to_check+1);
   187 }
   188 
   189 unsigned int x_check2(Trie *trie, char c1, char c2, unsigned int start=1)
   190 {
   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++)
   196 	{
   197 		if (base[i+_c1].mode == Node_Unused
   198 			&& base[i+_c2].mode == Node_Unused)
   199 		{
   200 			return i;
   201 		}
   202 	}
   203 
   204 	sm_trie_grow(trie);
   205 
   206 	return x_check2(trie, c1, c2, to_check+1);
   207 }
   208 
   209 unsigned int x_check_multi(Trie *trie, 
   210 							unsigned int offsets[], 
   211 							unsigned int count,
   212 							unsigned int start=1)
   213 {
   214 	TrieNode *base = trie->base;
   215 	TrieNode *cur;
   216 	unsigned int to_check = trie->baseSize;
   217 	unsigned int highest = 0;
   218 
   219 	for (unsigned int i=0; i<count; i++)
   220 	{
   221 		if (offsets[i] > highest)
   222 		{
   223 			highest = offsets[i];
   224 		}
   225 	}
   226 
   227 	to_check -= highest;
   228 
   229 	for (unsigned int i=start; i<=to_check; i++)
   230 	{
   231 		bool okay = true;
   232 		for (unsigned int j=0; j<count; j++)
   233 		{
   234 			cur = &base[i+offsets[j]];
   235 			if (cur->mode != Node_Unused)
   236 			{
   237 				okay = false;
   238 				break;
   239 			}
   240 		}
   241 		if (okay)
   242 		{
   243 			return i;
   244 		}
   245 	}
   246 
   247 	sm_trie_grow(trie);
   248 
   249 	return x_check_multi(trie, offsets, count, to_check+1);
   250 }
   251 
   252 unsigned int x_addstring(Trie *trie, const char *ptr)
   253 {
   254 	size_t len = strlen(ptr) + 1;
   255 
   256 	if (trie->tail + len >= trie->stSize)
   257 	{		
   258 		while (trie->tail + len >= trie->stSize)
   259 		{
   260 			trie->stSize *= 2;
   261 		}
   262 		trie->stringtab = (char *)realloc(trie->stringtab, trie->stSize);
   263 	}
   264 
   265 	unsigned int tail = trie->tail;
   266 	strcpy(&trie->stringtab[tail], ptr);
   267 	trie->tail += len;
   268 
   269 	return tail;
   270 }
   271 
   272 Trie *sm_trie_create()
   273 {
   274 	Trie *t = new Trie;
   275 
   276 	t->base = (TrieNode *)malloc(sizeof(TrieNode) * (256 + 1));
   277 	t->stringtab = (char *)malloc(sizeof(char) * 256);
   278 	t->baseSize = 256;
   279 	t->stSize = 256;
   280 
   281 	sm_trie_clear(t);
   282 
   283 	return t;
   284 }
   285 
   286 void sm_trie_clear(Trie *trie)
   287 {
   288 	trie->tail = 0;
   289 
   290 	memset(trie->base, 0, sizeof(TrieNode) * (trie->baseSize + 1));
   291 	memset(trie->stringtab, 0, sizeof(char) * trie->stSize);
   292 
   293 	/* Sentinel root node */
   294 	trie->base[1].idx = 1;
   295 	trie->base[1].mode = Node_Arc;
   296 	trie->base[1].parent = 1;
   297 }
   298 
   299 void sm_trie_destroy(Trie *trie)
   300 {
   301 	free(trie->base);
   302 	free(trie->stringtab);
   303 	delete trie;
   304 }
   305 
   306 bool sm_trie_delete(Trie *trie, const char *key)
   307 {
   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;
   313 
   314 	if (!*key)
   315 	{
   316 		return false;
   317 	}
   318 
   319 	/* Start traversing at the root node */
   320 	do
   321 	{
   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];
   327 		keyptr++;
   328 
   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)
   331 		{
   332 			return false;
   333 		} else if (node->mode == Node_Term) {
   334 			char *term = &trie->stringtab[node->idx];
   335 			if (strcmp(keyptr, term) == 0)
   336 			{
   337 				break;
   338 			}
   339 		}
   340 		lastidx = curidx;
   341 	} while (*keyptr != '\0');
   342 
   343 	assert(node != NULL);
   344 
   345 	if (!node->valset)
   346 	{
   347 		return false;
   348 	}
   349 
   350 	node->valset = false;
   351 	node->value = NULL;
   352 
   353 	return true;
   354 }
   355 
   356 bool sm_trie_retrieve(Trie *trie, const char *key, void **value)
   357 {
   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;
   363 
   364 	if (!*key)
   365 	{
   366 		return false;
   367 	}
   368 
   369 	/* Start traversing at the root node */
   370 	do
   371 	{
   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];
   377 		keyptr++;
   378 
   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)
   381 		{
   382 			return false;
   383 		} else if (node->mode == Node_Term) {
   384 			char *term = &trie->stringtab[node->idx];
   385 			if (strcmp(keyptr, term) == 0)
   386 			{
   387 				break;
   388 			}
   389 		}
   390 		lastidx = curidx;
   391 	} while (*keyptr != '\0');
   392 
   393 	assert(node != NULL);
   394 
   395 	if (!node->valset)
   396 	{
   397 		return false;
   398 	}
   399 
   400 	if (value)
   401 	{
   402 		*value = node->value;
   403 	}
   404 
   405 	return true;
   406 }
   407 
   408 bool sm_trie_add(Trie *trie, const char *key, void *value, bool replace_allowed)
   409 {
   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 */
   418 
   419 	/* Do not handle empty strings for simplicity */
   420 	if (!*key)
   421 	{
   422 		return false;
   423 	}
   424 
   425 	/* Start traversing at the root node (1) */
   426 	do
   427 	{
   428 		/* Find where the next character is, then advance */
   429 		curidx = base[lastidx].idx;
   430 		basenode = &base[curidx];
   431 		curoffs = charval(*keyptr);
   432 		curidx += curoffs;
   433 		node = &base[curidx];
   434 		keyptr++;
   435 
   436 		/* Check if this slot is supposed to be empty.  If so, we need to handle CASES 1/2:
   437 		 * Insertion without collisions
   438 		 */
   439 		if ( (curidx > trie->baseSize) || (node->mode == Node_Unused) )
   440 		{
   441 			if (curidx > trie->baseSize)
   442 			{
   443 				if (!sm_trie_grow(trie))
   444 				{
   445 					return false;
   446 				}
   447 				node = &trie->base[curidx];
   448 			}
   449 			node->parent = lastidx;
   450 			if (*keyptr == '\0')
   451 			{
   452 				node->mode = Node_Arc;
   453 			} else {
   454 				node->idx = x_addstring(trie, keyptr);
   455 				node->mode = Node_Term;
   456 			}
   457 			node->valset = true;
   458 			node->value = value;
   459 			
   460 			return true;
   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.
   467 			 *
   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.
   473 			 */
   474 			TrieNode *cur;
   475 			
   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.
   480 			 */
   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;
   486 
   487 			if (outgoing_base + outgoing_limit > trie->baseSize)
   488 			{
   489 				outgoing_limit = trie->baseSize - outgoing_base;
   490 			}
   491 
   492 			for (unsigned int i=1; i<=outgoing_limit; i++,cur++)
   493 			{
   494 				if (cur->mode == Node_Unused || cur->parent != lastidx)
   495 				{
   496 					continue;
   497 				}
   498 				outgoing_list[outgoing_count++] = i;
   499 			}
   500 			outgoing_list[outgoing_count++] = curidx - outgoing_base;
   501 
   502 			/* Now we need to find all the arcs leaving our parent...
   503 			 * Note: the inconsistency is the base of our parent.  
   504 			 */
   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;
   511 
   512 			if (incoming_base + incoming_limit > trie->baseSize)
   513 			{
   514 				incoming_limit = trie->baseSize - incoming_base;
   515 			}
   516 
   517 			assert(incoming_limit > 0 && incoming_limit <= 255);
   518 
   519 			for (unsigned int i=1; i<=incoming_limit; i++,cur++)
   520 			{
   521 				if (cur->mode == Node_Arc || cur->mode == Node_Term)
   522 				{
   523 					if (cur->parent == node->parent)
   524 					{
   525 						incoming_list[incoming_count++] = i;
   526 					}
   527 				}
   528 			}
   529 
   530 			if (incoming_count < outgoing_count + 1)
   531 			{
   532 				unsigned int q = x_check_multi(trie, incoming_list, incoming_count);
   533 
   534 				base = trie->base;
   535 				node = &base[curidx];
   536 
   537 				/* If we're incoming, we need to modify our parent */
   538 				base[node->parent].idx = q;
   539 
   540 				/* For each node in the "to move" list,
   541 				 * Relocate the node's info to the new position.
   542 				 */
   543 				unsigned int idx, newidx, oldidx;
   544 				for (unsigned int i=0; i<incoming_count; i++)
   545 				{
   546 					idx = incoming_list[i];
   547 					newidx = q + idx;
   548 					oldidx = incoming_base + idx;
   549 					if (oldidx == lastidx)
   550 					{
   551 						/* Important! Make sure we're not invalidating our sacred lastidx */
   552 						lastidx = newidx;
   553 					}
   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)
   559 					{
   560 						TrieNode *check_base = &base[base[newidx].idx] + 1;
   561 						for (unsigned int j=1; j<=255; j++, check_base++)
   562 						{
   563 							if (check_base->parent == oldidx)
   564 							{
   565 								check_base->parent = newidx;
   566 							}
   567 						}
   568 					}
   569 				}
   570 			} else {
   571 				unsigned int q = x_check_multi(trie, outgoing_list, outgoing_count);
   572 
   573 				base = trie->base;
   574 				node = &base[curidx];
   575 
   576 				/* If we're outgoing, we need to modify our own base */
   577 				base[lastidx].idx = q;
   578 
   579 				/* Take the last index (curidx) out of the list.  Technically we are not moving this,
   580 				 * since it's already being used by something else.  
   581 				 */
   582 				outgoing_count--;
   583 
   584 				/* For each node in the "to move" list,
   585 				 * Relocate the node's info to the new position.
   586 				 */
   587 				unsigned int idx, newidx, oldidx;
   588 				for (unsigned int i=0; i<outgoing_count; i++)
   589 				{
   590 					idx = outgoing_list[i];
   591 					newidx = q + idx;
   592 					oldidx = outgoing_base + idx;
   593 					if (oldidx == lastidx)
   594 					{
   595 						/* Important! Make sure we're not invalidating our sacred lastidx */
   596 						lastidx = newidx;
   597 					}
   598 					base[newidx] = base[oldidx];
   599 					assert(base[base[newidx].parent].mode == Node_Arc);
   600 					memset(&base[oldidx], 0, sizeof(TrieNode));
   601 					/* If we are not a terminator, we have children we must take care of */
   602 					if (base[newidx].mode == Node_Arc)
   603 					{
   604 						TrieNode *check_base = &base[base[newidx].idx] + 1;
   605 						for (unsigned int j=1; j<=255; j++, check_base++)
   606 						{
   607 							if (check_base->parent == oldidx)
   608 							{
   609 								check_base->parent = newidx;
   610 							}
   611 						}
   612 					}
   613 				}
   614 
   615 				/* Take the invisible node and use it as our new node */
   616 				node = &base[q + outgoing_list[outgoing_count]];
   617 			}
   618 
   619 			/* We're finally done! */
   620 			node->parent = lastidx;
   621 			if (*keyptr == '\0')
   622 			{
   623 				node->mode = Node_Arc;
   624 			} else {
   625 				node->idx = x_addstring(trie, keyptr);
   626 				node->mode = Node_Term;
   627 			}
   628 			node->valset = true;
   629 			node->value = value;
   630 
   631 			return true;
   632 		} else {
   633 			/* See what's in the next node - special case if terminator! */
   634 			if (node->mode == Node_Term)
   635 			{
   636 				/* If we're a terminator, we need to handle CASE 3:
   637 				 * Insertion when a terminating collision occurs
   638 				 */
   639 				char *term = &trie->stringtab[node->idx];
   640 				/* Do an initial browsing to make sure they're not the same string */
   641 				if (strcmp(keyptr, term) == 0)
   642 				{
   643 					if (!node->valset || replace_allowed)
   644 					{
   645 						node->valset = true;
   646 						node->value = value;
   647 						return true;
   648 					}
   649 					/* Same string.  We can't insert. */
   650 					return false;
   651 				}
   652 				/* For each matching character pair, we need to disband the terminator.
   653 				 * This splits the similar prefix into a single arc path.
   654 				 * First, save the old values so we can move them to a new node.
   655 				 * Next, for each loop:
   656 				 *  Take the current (invalid) node, and point it to the next arc base.
   657 				 *  Set the current node to the node at the next arc.
   658 				 */
   659 				void *oldvalue = node->value;
   660 				bool oldvalset = node->valset;
   661 				if (*term == *keyptr)
   662 				{
   663 				while (*term == *keyptr)
   664 				{
   665 					/* Find the next free slot in the check array.
   666 					 * This is the "vector base" essentially
   667 					 */
   668 					q = x_check(trie, *term);
   669 						base = trie->base;
   670 						node = &base[curidx];
   671 					/* Point the node to the next new base */
   672 					node->idx = q;
   673 					node->mode = Node_Arc;
   674 					node->valset = false;
   675 					/* Advance the input stream and local variables */
   676 					lastidx = curidx;
   677 					curidx = q + charval(*term);
   678 					node = &base[curidx];
   679 					/* Make sure the new current node has its parent set. */
   680 					node->parent = lastidx;
   681 					node->mode = Node_Arc;	/* Just in case we run x_check again */
   682 					*term = '\0';	/* Unmark the string table here */
   683 					term++;
   684 					keyptr++;
   685 					}
   686 				} else {
   687 					node->valset = false;
   688 				}
   689 				/* We're done inserting new pairs.  If one of them is exhausted,
   690 				 * we take special shortcuts.
   691 				 */
   692 				if (*term == '\0')				//EX: BADGERHOUSE added over B -> ADGER.  
   693 				{
   694 					/* First backpatch the current node - it ends the newly split terminator.
   695 					 * In the example, this would mean the node is the production from R -> ?
   696 					 * This node ends the old BADGER, so we set it here.
   697 					 */
   698 					node->valset = oldvalset;
   699 					node->value = oldvalue;
   700 
   701 					/* The terminator was split up, but pieces of keyptr remain.
   702 					 * We need to generate a new production, in this example, R -> H,
   703 					 * with H being a terminator to OUSE.  Thus we get:
   704 					 * B,A,D,G,E,R*,H*->OUSE (* = value set).
   705 					 * NOTE: parent was last set at the end of the while loop.
   706 					 */
   707 					/* Get the new base and apply re-basing */
   708 					q = x_check(trie, *keyptr);
   709 					base = trie->base;
   710 					node = &base[curidx];
   711 
   712 					node->idx = q;
   713 					node->mode = Node_Arc;
   714 					lastidx = curidx;
   715 					/* Finish the final node */
   716 					curidx = q + charval(*keyptr);
   717 					node = &trie->base[curidx];
   718 					keyptr++;
   719 					/* Optimize - don't add to string table if there's nothing more to eat */
   720 					if (*keyptr == '\0')
   721 					{
   722 						node->mode = Node_Arc;
   723 					} else {
   724 						node->idx = x_addstring(trie, keyptr);
   725 						node->mode = Node_Term;
   726 					}
   727 					node->parent = lastidx;
   728 					node->valset = true;
   729 					node->value = value;
   730 				} else if (*keyptr == '\0') {	//EX: BADGER added over B -> ADGERHOUSE
   731 					/* First backpatch the current node - it ends newly split input string.
   732 					 * This is the exact opposite of the above procedure.
   733 					 */
   734 					node->valset = true;
   735 					node->value = value;
   736 
   737 					/* Get the new base and apply re-basing */
   738 					q = x_check(trie, *term);
   739 					base = trie->base;
   740 					node = &base[curidx];
   741 
   742 					node->idx = q;
   743 					node->mode = Node_Arc;
   744 					lastidx = curidx;
   745 					/* Finish the final node */
   746 					curidx = q + charval(*term);
   747 					node = &trie->base[curidx];
   748 					term++;
   749 					/* Optimize - don't add to string table if there's nothing more to eat */
   750 					if (*term == '\0')
   751 					{
   752 						node->mode = Node_Arc;
   753 					} else {
   754 						node->idx = (term - trie->stringtab); /* Already in the string table! */
   755 						node->mode = Node_Term;
   756 					}
   757 					node->parent = lastidx;
   758 					node->valset = oldvalset;
   759 					node->value = oldvalue;
   760 				} else {
   761 					/* Finally, we have to create two new nodes instead of just one. */
   762 					node->mode = Node_Arc;
   763 					
   764 					/* Get the new base and apply re-basing */
   765 					q = x_check2(trie, *keyptr, *term);
   766 					base = trie->base;
   767 					node = &base[curidx];
   768 
   769 					node->idx = q;
   770 					lastidx = curidx;
   771 
   772 					/* Re-create the old terminated node */
   773 					curidx = q + charval(*term);
   774 					node = &trie->base[curidx];
   775 					term++;
   776 					node->valset = oldvalset;
   777 					node->value = oldvalue;
   778 					node->parent = lastidx;
   779 					if (*term == '\0')
   780 					{
   781 						node->mode = Node_Arc;
   782 					} else {
   783 						node->mode = Node_Term;
   784 						node->idx = (term - trie->stringtab); /* Already in the string table! */
   785 					}
   786 
   787 					/* Create the new keyed input node */
   788 					curidx = q + charval(*keyptr);
   789 					node = &trie->base[curidx];
   790 					keyptr++;
   791 					node->valset = true;
   792 					node->value = value;
   793 					node->parent = lastidx;
   794 					if (*keyptr == '\0')
   795 					{
   796 						node->mode = Node_Arc;
   797 					} else {
   798 						node->mode = Node_Term;
   799 						node->idx = x_addstring(trie, keyptr);
   800 					}
   801 				}
   802 
   803 				/* Phew! */
   804 				return true;
   805 			} else {
   806 				assert(node->mode == Node_Arc);
   807 			}
   808 		}
   809 		lastidx = curidx;
   810 	} while (*keyptr != '\0');
   811 
   812 	assert(node);
   813 
   814 	/* If we've exhausted the string and we have a valid reached node,
   815 	 * the production rule already existed.  Make sure it's valid to set first.
   816 	 */
   817 
   818 	/* We have to be an Arc.  If the last result was anything else, we would have returned a new 
   819 	 * production earlier.
   820 	 */
   821 	assert(node->mode == Node_Arc);
   822 
   823 	if (!node->valset || replace_allowed)
   824 	{
   825 		/* Insert is only possible if we have no production */
   826 		node->valset = true;
   827 		node->value = value;
   828 		return true;
   829 	}
   830 
   831 	return false;
   832 }
   833 
   834 bool sm_trie_insert(Trie *trie, const char *key, void *value)
   835 {
   836 	return sm_trie_add(trie, key, value, false);
   837 }
   838 
   839 bool sm_trie_replace(Trie *trie, const char *key, void *value)
   840 {
   841 	return sm_trie_add(trie, key, value, true);
   842 }