ipc.c: Adding Andrews become_root code to the main branch.
[samba.git] / source3 / ubiqx / ubi_BinTree.c
1 /* ========================================================================== **
2  *                              ubi_BinTree.c
3  *
4  *  Copyright (C) 1991-1997 by Christopher R. Hertel
5  *
6  *  Email:  crh@ubiqx.mn.org
7  * -------------------------------------------------------------------------- **
8  *
9  *  ubi_BinTree manages a simple binary tree.  Nothing fancy here.  No height
10  *  balancing, no restructuring.  Still, a good tool for creating short, low-
11  *  overhead sorted lists of things that need to be found in a hurry.
12  *
13  *  In addition, this module provides a good basis for creating other types
14  *  of binary tree handling modules.
15  *
16  * -------------------------------------------------------------------------- **
17  *
18  *  This library is free software; you can redistribute it and/or
19  *  modify it under the terms of the GNU Library General Public
20  *  License as published by the Free Software Foundation; either
21  *  version 2 of the License, or (at your option) any later version.
22  *
23  *  This library is distributed in the hope that it will be useful,
24  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
25  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
26  *  Library General Public License for more details.
27  *
28  *  You should have received a copy of the GNU Library General Public
29  *  License along with this library; if not, write to the Free
30  *  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
31  *
32  * -------------------------------------------------------------------------- **
33  *
34  * $Log: ubi_BinTree.c,v $
35  * Revision 1.1  1997/10/10 14:46:38  crh
36  * This is the ubiqx binary tree and linked list library.
37  * This library is being included as part of the Samba distribution.
38  * (Hurray!)
39  *
40  * Revision 2.4  1997/07/26 04:11:10  crh
41  * + Just to be annoying I changed ubi_TRUE and ubi_FALSE to ubi_trTRUE
42  *   and ubi_trFALSE.
43  * + There is now a type ubi_trBool to go with ubi_trTRUE and ubi_trFALSE.
44  * + There used to be something called "ubi_TypeDefs.h".  I got rid of it.
45  * + Added function ubi_btLeafNode().
46  *
47  * Revision 2.3  1997/06/03 05:16:17  crh
48  * Changed TRUE and FALSE to ubi_TRUE and ubi_FALSE to avoid conflicts.
49  * Also changed the interface to function InitTree().  See the comments
50  * for this function for more information.
51  *
52  * Revision 2.2  1995/10/03 22:00:07  CRH
53  * Ubisized!
54  * 
55  * Revision 2.1  95/03/09  23:37:10  CRH
56  * Added the ModuleID static string and function.  These modules are now
57  * self-identifying.
58  * 
59  * Revision 2.0  95/02/27  22:00:17  CRH
60  * Revision 2.0 of this program includes the following changes:
61  *
62  *     1)  A fix to a major typo in the RepaceNode() function.
63  *     2)  The addition of the static function Border().
64  *     3)  The addition of the public functions FirstOf() and LastOf(), which
65  *         use Border(). These functions are used with trees that allow
66  *         duplicate keys.
67  *     4)  A complete rewrite of the Locate() function.  Locate() now accepts
68  *         a "comparison" operator.
69  *     5)  Overall enhancements to both code and comments.
70  *
71  * I decided to give this a new major rev number because the interface has
72  * changed.  In particular, there are two new functions, and changes to the
73  * Locate() function.
74  *
75  * Revision 1.0  93/10/15  22:44:59  CRH
76  * With this revision, I have added a set of #define's that provide a single,
77  * standard API to all existing tree modules.  Until now, each of the three
78  * existing modules had a different function and typedef prefix, as follows:
79  *
80  *       Module        Prefix
81  *     ubi_BinTree     ubi_bt
82  *     ubi_AVLtree     ubi_avl
83  *     ubi_SplayTree   ubi_spt
84  *
85  * To further complicate matters, only those portions of the base module
86  * (ubi_BinTree) that were superceeded in the new module had the new names.
87  * For example, if you were using ubi_AVLtree, the AVL node structure was
88  * named "ubi_avlNode", but the root structure was still "ubi_btRoot".  Using
89  * SplayTree, the locate function was called "ubi_sptLocate", but the next
90  * and previous functions remained "ubi_btNext" and "ubi_btPrev".
91  *
92  * This was not too terrible if you were familiar with the modules and knew
93  * exactly which tree model you wanted to use.  If you wanted to be able to
94  * change modules (for speed comparisons, etc), things could get messy very
95  * quickly.
96  *
97  * So, I have added a set of defined names that get redefined in any of the
98  * descendant modules.  To use this standardized interface in your code,
99  * simply replace all occurances of "ubi_bt", "ubi_avl", and "ubi_spt" with
100  * "ubi_tr".  The "ubi_tr" names will resolve to the correct function or
101  * datatype names for the module that you are using.  Just remember to
102  * include the header for that module in your program file.  Because these
103  * names are handled by the preprocessor, there is no added run-time
104  * overhead.
105  *
106  * Note that the original names do still exist, and can be used if you wish
107  * to write code directly to a specific module.  This should probably only be
108  * done if you are planning to implement a new descendant type, such as
109  * red/black trees.  CRH
110  *
111  *  V0.0 - June, 1991   -  Written by Christopher R. Hertel (CRH).
112  *
113  * ========================================================================== **
114  */
115
116 #include "ubi_BinTree.h"            /* Header for this module          */
117 #include <stdlib.h>                 /* Standard C definitions.         */
118
119 /* ========================================================================== **
120  * Static data.
121  */
122
123 static char ModuleID[] = "ubi_BinTree\n\
124 \t$Revision: 1.1 $\n\
125 \t$Date: 1997/10/10 14:46:38 $\n\
126 \t$Author: crh $\n";
127
128 /* ========================================================================== **
129  * Internal (private) functions.
130  */
131
132 static ubi_btNodePtr qFind( ubi_btCompFunc cmp,
133                             ubi_btItemPtr  FindMe,
134                    register ubi_btNodePtr  p )
135   /* ------------------------------------------------------------------------ **
136    * This function performs a non-recursive search of a tree for a node
137    * matching a specific key.  It is called "qFind()" because it is
138    * faster that TreeFind (below).
139    *
140    *  Input:
141    *     cmp      -  a pointer to the tree's comparison function.
142    *     FindMe   -  a pointer to the key value for which to search.
143    *     p        -  a pointer to the starting point of the search.  <p>
144    *                 is considered to be the root of a subtree, and only
145    *                 the subtree will be searched.
146    *
147    *  Output:
148    *     A pointer to a node with a key that matches the key indicated by
149    *     FindMe, or NULL if no such node was found.
150    *
151    *  Note:   In a tree that allows duplicates, the pointer returned *might
152    *          not* point to the (sequentially) first occurance of the
153    *          desired key.
154    * ------------------------------------------------------------------------ **
155    */
156   {
157   char tmp;
158
159   while( p && (( tmp = AbNormal((*cmp)(FindMe, p)) ) != EQUAL) )
160     p = p->Link[tmp];
161
162   return( p );
163   } /* qFind */
164
165 static ubi_btNodePtr TreeFind( ubi_btItemPtr  findme,
166                                ubi_btNodePtr  p,
167                                ubi_btNodePtr *parentp,
168                                char          *gender,
169                                ubi_btCompFunc CmpFunc )
170   /* ------------------------------------------------------------------------ **
171    * TreeFind() searches a tree for a given value (findme).  It will return a
172    * pointer to the target node, if found, or NULL if the target node was not
173    * found.
174    *
175    * TreeFind() also returns, via parameters, a pointer to the parent of the
176    * target node, and a LEFT or RIGHT value indicating which child of the
177    * parent is the target node.  *If the target is not found*, then these
178    * values indicate the place at which the target *should be found*.  This
179    * is useful when inserting a new node into a tree or searching for nodes
180    * "near" the target node.
181    *
182    * The parameters are:
183    *
184    *  findme   -  is a pointer to the key information to be searched for.
185    *  p        -  points to the root of the tree to be searched.
186    *  parentp  -  will return a pointer to a pointer to the !parent! of the
187    *              target node, which can be especially usefull if the target
188    *              was not found.
189    *  gender   -  returns LEFT or RIGHT to indicate which child of *parentp
190    *              was last searched.
191    *  CmpFunc  -  points to the comparison function.
192    *
193    * This function is called by ubi_btLocate() and ubi_btInsert().
194    * ------------------------------------------------------------------------ **
195    */
196   {
197   register ubi_btNodePtr tmp_p = p;
198   ubi_btNodePtr tmp_pp = NULL;
199   char tmp_sex = EQUAL;
200   char tmp_cmp;
201
202   while( tmp_p && (EQUAL != (tmp_cmp = AbNormal((*CmpFunc)(findme, tmp_p)))) )
203     {
204     tmp_pp  = tmp_p;                /* Keep track of previous node. */
205     tmp_sex = tmp_cmp;              /* Keep track of sex of child.  */
206     tmp_p = tmp_p->Link[tmp_cmp];   /* Go to child. */
207     }
208   *parentp = tmp_pp;                /* Return results. */
209   *gender  = tmp_sex;
210   return( tmp_p );
211   } /* TreeFind */
212
213 static void ReplaceNode( ubi_btNodePtr *parent,
214                          ubi_btNodePtr  oldnode,
215                          ubi_btNodePtr  newnode )
216   /* ------------------------------------------------------------------ *
217    * Remove node oldnode from the tree, replacing it with node newnode.
218    *
219    * Input:
220    *  parent   - A pointer to he parent pointer of the node to be
221    *             replaced.  <parent> may point to the Link[] field of
222    *             a parent node, or it may indicate the root pointer at
223    *             the top of the tree.
224    *  oldnode  - A pointer to the node that is to be replaced.
225    *  newnode  - A pointer to the node that is to be installed in the
226    *             place of <*oldnode>.
227    *
228    * Notes:    Don't forget to free oldnode.
229    *           Also, this function used to have a really nasty typo
230    *           bug.  "oldnode" and "newnode" were swapped in the line
231    *           that now reads:
232    *     ((unsigned char *)newnode)[i] = ((unsigned char *)oldnode)[i];
233    *           Bleah!
234    * ------------------------------------------------------------------ *
235    */
236   {
237   register int i;
238   register int btNodeSize = sizeof( ubi_btNode );
239
240   for( i = 0; i < btNodeSize; i++ ) /* Copy node internals to new node. */
241     ((unsigned char *)newnode)[i] = ((unsigned char *)oldnode)[i];
242   (*parent) = newnode;              /* Old node's parent points to new child. */
243   /* Now tell the children about their new step-parent. */
244   if( oldnode->Link[LEFT ] ) (oldnode->Link[LEFT ])->Link[PARENT] = newnode;
245   if( oldnode->Link[RIGHT] ) (oldnode->Link[RIGHT])->Link[PARENT] = newnode;
246   } /* ReplaceNode */
247
248 static void SwapNodes( ubi_btRootPtr RootPtr,
249                        ubi_btNodePtr Node1,
250                        ubi_btNodePtr Node2 )
251   /* ------------------------------------------------------------------------ **
252    * This function swaps two nodes in the tree.  Node1 will take the place of
253    * Node2, and Node2 will fill in the space left vacant by Node 1.
254    *
255    * Input:
256    *  RootPtr  - pointer to the tree header structure for this tree.
257    *  Node1    - \
258    *              > These are the two nodes which are to be swapped.
259    *  Node2    - /
260    *
261    * Notes:
262    *  This function does a three step swap, using a dummy node as a place
263    *  holder.  This function is used by ubi_btRemove().
264    * ------------------------------------------------------------------------ **
265    */
266   {
267   ubi_btNodePtr *Parent;
268   ubi_btNode     dummy;
269   ubi_btNodePtr  dummy_p = &dummy;
270
271   /* Replace Node 1 with the dummy, thus removing Node1 from the tree. */
272   if( Node1->Link[PARENT] )
273     Parent = &((Node1->Link[PARENT])->Link[Node1->gender]);
274   else
275     Parent = &(RootPtr->root);
276   ReplaceNode( Parent, Node1, dummy_p );
277
278   /* Swap Node 1 with Node 2, placing Node 1 back into the tree. */
279   if( Node2->Link[PARENT] )
280     Parent = &((Node2->Link[PARENT])->Link[Node2->gender]);
281   else
282     Parent = &(RootPtr->root);
283   ReplaceNode( Parent, Node2, Node1 );
284
285   /* Swap Node 2 and the dummy, thus placing Node 2 back into the tree. */
286   if( dummy_p->Link[PARENT] )
287     Parent = &((dummy_p->Link[PARENT])->Link[dummy_p->gender]);
288   else
289     Parent = &(RootPtr->root);
290   ReplaceNode( Parent, dummy_p, Node2 );
291   } /* SwapNodes */
292
293 /* -------------------------------------------------------------------------- **
294  * These routines allow you to walk through the tree, forwards or backwards.
295  */
296
297 static ubi_btNodePtr SubSlide( register ubi_btNodePtr P,
298                                register char  whichway )
299   /* ------------------------------------------------------------------------ **
300    * Slide down the side of a subtree.
301    *
302    * Given a starting node, this function returns a pointer to the LEFT-, or
303    * RIGHT-most descendent, *or* (if whichway is PARENT) to the tree root.
304    *
305    *  Input:  P         - a pointer to a starting place.
306    *          whichway  - the direction (LEFT, RIGHT, or PARENT) in which to
307    *                      travel.
308    *  Output: A pointer to a node that is either the root, or has no
309    *          whichway-th child but is within the subtree of P.  Note that
310    *          the return value may be the same as P.  The return value *will
311    *          be* NULL if P is NULL.
312    * ------------------------------------------------------------------------ **
313    */
314   {
315   ubi_btNodePtr Q = NULL;
316
317   while( P )
318     {
319     Q = P;
320     P = P->Link[ whichway ];
321     }
322   return( Q );
323   } /* SubSlide */
324
325 static ubi_btNodePtr Neighbor( register ubi_btNodePtr P,
326                                register char  whichway )
327   /* ------------------------------------------------------------------------ **
328    * Given starting point p, return the (key order) next or preceeding node
329    * in the tree.
330    *
331    *  Input:  P         - Pointer to our starting place node.
332    *          whichway  - the direction in which to travel to find the
333    *                      neighbor, i.e., the RIGHT neighbor or the LEFT
334    *                      neighbor.
335    *
336    *  Output: A pointer to the neighboring node, or NULL if P was NULL.
337    *
338    *  Notes:  If whichway is PARENT, the results are unpredictable.
339    * ------------------------------------------------------------------------ **
340    */
341   {
342   if( P )
343     {
344     if( P->Link[ whichway ] )
345       return( SubSlide( P->Link[ whichway ], (char)RevWay(whichway) ) );
346     else
347       while( P->Link[ PARENT ] )
348         {
349         if( (P->Link[ PARENT ])->Link[ whichway ] == P )
350           P = P->Link[ PARENT ];
351         else
352           return( P->Link[ PARENT ] );
353         }
354     }
355   return( NULL );
356   } /* Neighbor */
357
358 static ubi_btNodePtr Border( ubi_btRootPtr RootPtr,
359                              ubi_btItemPtr FindMe,
360                              ubi_btNodePtr p,
361                              char          whichway )
362   /* ------------------------------------------------------------------------ **
363    * Given starting point p, which has a key value equal to *FindMe, locate
364    * the first (index order) node with the same key value.
365    *
366    * This function is useful in trees that have can have duplicate keys.
367    * For example, consider the following tree:
368    *     Tree                                                      Traversal
369    *       2    If <p> points to the root and <whichway> is RIGHT,     3
370    *      / \    then the return value will be a pointer to the       / \
371    *     2   2    RIGHT child of the root node.  The tree on         2   5
372    *    /   / \    the right shows the order of traversal.          /   / \
373    *   1   2   3                                                   1   4   6
374    *
375    *  Input:  RootPtr   - Pointer to the tree root structure.
376    *          FindMe    - Key value for comparisons.
377    *          p         - Pointer to the starting-point node.
378    *          whichway  - the direction in which to travel to find the
379    *                      neighbor, i.e., the RIGHT neighbor or the LEFT
380    *                      neighbor.
381    *
382    *  Output: A pointer to the first (index, or "traversal", order) node with
383    *          a Key value that matches *FindMe.
384    *
385    *  Notes:  If whichway is PARENT, or if the tree does not allow duplicate
386    *          keys, this function will return <p>.
387    * ------------------------------------------------------------------------ **
388    */
389   {
390   register ubi_btNodePtr q;
391
392   /* Exit if there's nothing that can be done. */
393   if( !Dups_OK( RootPtr ) || (PARENT == whichway) )
394     return( p );
395
396   /* First, if needed, move up the tree.  We need to get to the root of the
397    * subtree that contains all of the matching nodes.
398    */
399   q = p->Link[PARENT];
400   while( q && (EQUAL == AbNormal( (*(RootPtr->cmp))(FindMe, q) )) )
401     {
402     p = q;
403     q = p->Link[PARENT];
404     }
405
406   /* Next, move back down in the "whichway" direction. */
407   q = p->Link[whichway];
408   while( q )
409     {
410     if( q = qFind( RootPtr->cmp, FindMe, q ) )
411       {
412       p = q;
413       q = p->Link[whichway];
414       }
415     }
416   return( p );
417   } /* Border */
418
419
420 /* ========================================================================== **
421  * Exported utilities.
422  */
423
424 long ubi_btSgn( register long x )
425   /* ------------------------------------------------------------------------ **
426    * Return the sign of x; {negative,zero,positive} ==> {-1, 0, 1}.
427    *
428    *  Input:  x - a signed long integer value.
429    *
430    *  Output: the "sign" of x, represented as follows:
431    *            -1 == negative
432    *             0 == zero (no sign)
433    *             1 == positive
434    *
435    * Note: This utility is provided in order to facilitate the conversion
436    *       of C comparison function return values into BinTree direction
437    *       values: {LEFT, PARENT, EQUAL}.  It is INCORPORATED into the
438    *       AbNormal() conversion macro!
439    *
440    * ------------------------------------------------------------------------ **
441    */
442   {
443   return( (x)?((x>0)?(1):(-1)):(0) );
444   } /* ubi_btSgn */
445
446 ubi_btNodePtr ubi_btInitNode( ubi_btNodePtr NodePtr )
447   /* ------------------------------------------------------------------------ **
448    * Initialize a tree node.
449    *
450    *  Input:  a pointer to a ubi_btNode structure to be initialized.
451    *  Output: a pointer to the initialized ubi_btNode structure (ie. the
452    *          same as the input pointer).
453    * ------------------------------------------------------------------------ **
454    */
455   {
456   NodePtr->Link[ LEFT ]   = NULL;
457   NodePtr->Link[ PARENT ] = NULL;
458   NodePtr->Link[ RIGHT ]  = NULL;
459   NodePtr->gender         = EQUAL;
460   return( NodePtr );
461   } /* ubi_btInitNode */
462
463 ubi_btRootPtr ubi_btInitTree( ubi_btRootPtr   RootPtr,
464                               ubi_btCompFunc  CompFunc,
465                               unsigned char   Flags )
466   /* ------------------------------------------------------------------------ **
467    * Initialize the fields of a Tree Root header structure.
468    *
469    *  Input:   RootPtr   - a pointer to an ubi_btRoot structure to be
470    *                       initialized.
471    *           CompFunc  - a pointer to a comparison function that will be used
472    *                       whenever nodes in the tree must be compared against
473    *                       outside values.
474    *           Flags     - One bytes worth of flags.  Flags include
475    *                       ubi_trOVERWRITE and ubi_trDUPKEY.  See the header
476    *                       file for more info.
477    *
478    *  Output:  a pointer to the initialized ubi_btRoot structure (ie. the
479    *           same value as RootPtr).
480    *
481    *  Note:    The interface to this function has changed from that of
482    *           previous versions.  The <Flags> parameter replaces two
483    *           boolean parameters that had the same basic effect.
484    *
485    * ------------------------------------------------------------------------ **
486    */
487   {
488   if( RootPtr )
489     {
490     RootPtr->root   = NULL;
491     RootPtr->count  = 0L;
492     RootPtr->cmp    = CompFunc;
493     RootPtr->flags  = (Flags & ubi_trDUPKEY) ? ubi_trDUPKEY : Flags;
494     }                 /* There are only two supported flags, and they are
495                        * mutually exclusive.  ubi_trDUPKEY takes precedence
496                        * over ubi_trOVERWRITE.
497                        */
498   return( RootPtr );
499   } /* ubi_btInitTree */
500
501 ubi_trBool ubi_btInsert( ubi_btRootPtr  RootPtr,
502                          ubi_btNodePtr  NewNode,
503                          ubi_btItemPtr  ItemPtr,
504                          ubi_btNodePtr *OldNode )
505   /* ------------------------------------------------------------------------ **
506    * This function uses a non-recursive algorithm to add a new element to the
507    * tree.
508    *
509    *  Input:   RootPtr  -  a pointer to the ubi_btRoot structure that indicates
510    *                       the root of the tree to which NewNode is to be added.
511    *           NewNode  -  a pointer to an ubi_btNode structure that is NOT
512    *                       part of any tree.
513    *           ItemPtr  -  A pointer to the sort key that is stored within
514    *                       *NewNode.  ItemPtr MUST point to information stored
515    *                       in *NewNode or an EXACT DUPLICATE.  The key data
516    *                       indicated by ItemPtr is used to place the new node
517    *                       into the tree.
518    *           OldNode  -  a pointer to an ubi_btNodePtr.  When searching
519    *                       the tree, a duplicate node may be found.  If
520    *                       duplicates are allowed, then the new node will
521    *                       be simply placed into the tree.  If duplicates
522    *                       are not allowed, however, then one of two things
523    *                       may happen.
524    *                       1) if overwritting *is not* allowed, this
525    *                          function will return FALSE (indicating that
526    *                          the new node could not be inserted), and
527    *                          *OldNode will point to the duplicate that is
528    *                          still in the tree.
529    *                       2) if overwritting *is* allowed, then this
530    *                          function will swap **OldNode for *NewNode.
531    *                          In this case, *OldNode will point to the node
532    *                          that was removed (thus allowing you to free
533    *                          the node).
534    *                          **  If you are using overwrite mode, ALWAYS  **
535    *                          ** check the return value of this parameter! **
536    *                 Note: You may pass NULL in this parameter, the
537    *                       function knows how to cope.  If you do this,
538    *                       however, there will be no way to return a
539    *                       pointer to an old (ie. replaced) node (which is
540    *                       a problem if you are using overwrite mode).
541    *
542    *  Output:  a boolean value indicating success or failure.  The function
543    *           will return FALSE if the node could not be added to the tree.
544    *           Such failure will only occur if duplicates are not allowed,
545    *           nodes cannot be overwritten, AND a duplicate key was found
546    *           within the tree.
547    * ------------------------------------------------------------------------ **
548    */
549   {
550   ubi_btNodePtr OtherP,
551                 parent = NULL;
552   char          tmp;
553
554   if( !(OldNode) )       /* If they didn't give us a pointer, supply our own. */
555     OldNode = &OtherP;
556
557   (void)ubi_btInitNode( NewNode );     /* Init the new node's BinTree fields. */
558
559   /* Find a place for the new node. */
560   *OldNode = TreeFind(ItemPtr, (RootPtr->root), &parent, &tmp, (RootPtr->cmp));
561
562   /* Now add the node to the tree... */
563   if (!(*OldNode)) /* The easy one: we have a space for a new node! */
564     {
565     if (!(parent))
566       RootPtr->root = NewNode;
567     else
568       {
569       parent->Link[tmp]     = NewNode;
570       NewNode->Link[PARENT] = parent;
571       NewNode->gender       = tmp;
572       }
573     (RootPtr->count)++;
574     return( ubi_trTRUE );
575     }
576
577   /* If we reach this point, we know that a duplicate node exists.  This
578    * section adds the node to the tree if duplicate keys are allowed.
579    */
580   if( Dups_OK(RootPtr) )    /* Key exists, add duplicate */
581     {
582     ubi_btNodePtr q;
583
584     tmp = RIGHT;
585     q = (*OldNode);
586     *OldNode = NULL;
587     while( q )
588       {
589       parent = q;
590       if( tmp == EQUAL ) tmp = RIGHT;
591       q = q->Link[tmp];
592       if ( q )
593         tmp = AbNormal( (*(RootPtr->cmp))(ItemPtr, q) );
594       }
595     parent->Link[tmp]      = NewNode;
596     NewNode->Link[PARENT]  = parent;
597     NewNode->gender        = tmp;
598     (RootPtr->count)++;
599     return( ubi_trTRUE );
600     }
601
602   /* If we get to *this* point, we know that we are not allowed to have
603    * duplicate nodes, but our node keys match, so... may we replace the
604    * old one?
605    */
606   if( Ovwt_OK(RootPtr) )    /* Key exists, we replace */
607     {
608     if (!(parent))
609       ReplaceNode( &(RootPtr->root), *OldNode, NewNode );
610     else
611       ReplaceNode( &(parent->Link[(*OldNode)->gender]), *OldNode, NewNode );
612     return( ubi_trTRUE );
613     }
614
615   return( ubi_trFALSE );      /* Failure: could not replace an existing node. */
616   } /* ubi_btInsert */
617
618 ubi_btNodePtr ubi_btRemove( ubi_btRootPtr RootPtr,
619                             ubi_btNodePtr DeadNode )
620   /* ------------------------------------------------------------------------ **
621    * This function removes the indicated node from the tree.
622    *
623    *  Input:   RootPtr  -  A pointer to the header of the tree that contains
624    *                       the node to be removed.
625    *           DeadNode -  A pointer to the node that will be removed.
626    *
627    *  Output:  This function returns a pointer to the node that was removed
628    *           from the tree (ie. the same as DeadNode).
629    *
630    *  Note:    The node MUST be in the tree indicated by RootPtr.  If not,
631    *           strange and evil things will happen to your trees.
632    * ------------------------------------------------------------------------ **
633    */
634   {
635   ubi_btNodePtr p,
636                *parentp;
637   char          tmp;
638
639   /* if the node has both left and right subtrees, then we have to swap
640    * it with another node.  The other node we choose will be the Prev()ious
641    * node, which is garunteed to have no RIGHT child.
642    */
643   if( (DeadNode->Link[LEFT]) && (DeadNode->Link[RIGHT]) )
644     SwapNodes( RootPtr, DeadNode, ubi_btPrev( DeadNode ) );
645
646   /* The parent of the node to be deleted may be another node, or it may be
647    * the root of the tree.  Since we're not sure, it's best just to have
648    * a pointer to the parent pointer, whatever it is.
649    */
650   if (DeadNode->Link[PARENT])
651     parentp = &((DeadNode->Link[PARENT])->Link[DeadNode->gender]);
652   else
653     parentp = &( RootPtr->root );
654
655   /* Now link the parent to the only grand-child and patch up the gender. */
656   tmp = ((DeadNode->Link[LEFT])?LEFT:RIGHT);
657
658   p = (DeadNode->Link[tmp]);
659   if( p )
660     {
661     p->Link[PARENT] = DeadNode->Link[PARENT];
662     p->gender       = DeadNode->gender;
663     }
664   (*parentp) = p;
665
666   /* Finished, reduce the node count and return. */
667   (RootPtr->count)--;
668   return( DeadNode );
669   } /* ubi_btRemove */
670
671 ubi_btNodePtr ubi_btLocate( ubi_btRootPtr RootPtr,
672                             ubi_btItemPtr FindMe,
673                             ubi_trCompOps CompOp )
674   /* ------------------------------------------------------------------------ **
675    * The purpose of ubi_btLocate() is to find a node or set of nodes given
676    * a target value and a "comparison operator".  The Locate() function is
677    * more flexible and (in the case of trees that may contain dupicate keys)
678    * more precise than the ubi_btFind() function.  The latter is faster,
679    * but it only searches for exact matches and, if the tree contains
680    * duplicates, Find() may return a pointer to any one of the duplicate-
681    * keyed records.
682    *
683    *  Input:
684    *     RootPtr  -  A pointer to the header of the tree to be searched.
685    *     FindMe   -  An ubi_btItemPtr that indicates the key for which to
686    *                 search.
687    *     CompOp   -  One of the following:
688    *                    CompOp     Return a pointer to the node with
689    *                    ------     ---------------------------------
690    *                   ubi_trLT - the last key value that is less
691    *                              than FindMe.
692    *                   ubi_trLE - the first key matching FindMe, or
693    *                              the last key that is less than
694    *                              FindMe.
695    *                   ubi_trEQ - the first key matching FindMe.
696    *                   ubi_trGE - the first key matching FindMe, or the
697    *                              first key greater than FindMe.
698    *                   ubi_trGT - the first key greater than FindMe.
699    *  Output:
700    *     A pointer to the node matching the criteria listed above under
701    *     CompOp, or NULL if no node matched the criteria.
702    *
703    *  Notes:
704    *     In the case of trees with duplicate keys, Locate() will behave as
705    *     follows:
706    *
707    *     Find:  3                       Find: 3
708    *     Keys:  1 2 2 2 3 3 3 3 3 4 4   Keys: 1 1 2 2 2 4 4 5 5 5 6
709    *                  ^ ^         ^                   ^ ^
710    *                 LT EQ        GT                 LE GE
711    *
712    *     That is, when returning a pointer to a node with a key that is LESS
713    *     THAN the target key (FindMe), Locate() will return a pointer to the
714    *     LAST matching node.
715    *     When returning a pointer to a node with a key that is GREATER
716    *     THAN the target key (FindMe), Locate() will return a pointer to the
717    *     FIRST matching node.
718    *
719    *  See Also: ubi_btFind(), ubi_btFirstOf(), ubi_btLastOf().
720    * ------------------------------------------------------------------------ **
721    */
722   {
723   register ubi_btNodePtr p;
724   ubi_btNodePtr   parent;
725   char            whichkid;
726
727   /* Start by searching for a matching node. */
728   p = TreeFind( FindMe,
729                 RootPtr->root,
730                 &parent,
731                 &whichkid,
732                 RootPtr->cmp );
733
734   if( p )   /* If we have found a match, we can resolve as follows: */
735     {
736     switch( CompOp )
737       {
738       case ubi_trLT:            /* It's just a jump to the left...  */
739         p = Border( RootPtr, FindMe, p, LEFT );
740         return( Neighbor( p, LEFT ) );
741       case ubi_trGT:            /* ...and then a jump to the right. */
742         p = Border( RootPtr, FindMe, p, RIGHT );
743         return( Neighbor( p, RIGHT ) );
744       }
745     p = Border( RootPtr, FindMe, p, LEFT );
746     return( p );
747     }
748
749   /* Else, no match. */
750   if( ubi_trEQ == CompOp )    /* If we were looking for an exact match... */
751     return( NULL );           /* ...forget it.                            */
752
753   /* We can still return a valid result for GT, GE, LE, and LT.
754    * <parent> points to a node with a value that is either just before or
755    * just after the target value.
756    * Remaining possibilities are LT and GT (including LE & GE).
757    */
758   if( (ubi_trLT == CompOp) || (ubi_trLE == CompOp) )
759     return( (LEFT  == whichkid) ? Neighbor( parent, whichkid ) : parent );
760   else
761     return( (RIGHT == whichkid) ? Neighbor( parent, whichkid ) : parent );
762   } /* ubi_btLocate */
763
764 ubi_btNodePtr ubi_btFind( ubi_btRootPtr RootPtr,
765                           ubi_btItemPtr FindMe )
766   /* ------------------------------------------------------------------------ **
767    * This function performs a non-recursive search of a tree for any node
768    * matching a specific key.
769    *
770    *  Input:
771    *     RootPtr  -  a pointer to the header of the tree to be searched.
772    *     FindMe   -  a pointer to the key value for which to search.
773    *
774    *  Output:
775    *     A pointer to a node with a key that matches the key indicated by
776    *     FindMe, or NULL if no such node was found.
777    *
778    *  Note:   In a tree that allows duplicates, the pointer returned *might
779    *          not* point to the (sequentially) first occurance of the
780    *          desired key.  In such a tree, it may be more useful to use
781    *          ubi_btLocate().
782    * ------------------------------------------------------------------------ **
783    */
784   {
785   return( qFind( RootPtr->cmp, FindMe, RootPtr->root ) );
786   } /* ubi_btFind */
787
788 ubi_btNodePtr ubi_btNext( ubi_btNodePtr P )
789   /* ------------------------------------------------------------------------ **
790    * Given the node indicated by P, find the (sorted order) Next node in the
791    * tree.
792    *  Input:   P  -  a pointer to a node that exists in a binary tree.
793    *  Output:  A pointer to the "next" node in the tree, or NULL if P pointed
794    *           to the "last" node in the tree or was NULL.
795    * ------------------------------------------------------------------------ **
796    */
797   {
798   return( Neighbor( P, RIGHT ) );
799   } /* ubi_btNext */
800
801 ubi_btNodePtr ubi_btPrev( ubi_btNodePtr P )
802   /* ------------------------------------------------------------------------ **
803    * Given the node indicated by P, find the (sorted order) Previous node in
804    * the tree.
805    *  Input:   P  -  a pointer to a node that exists in a binary tree.
806    *  Output:  A pointer to the "previous" node in the tree, or NULL if P
807    *           pointed to the "first" node in the tree or was NULL.
808    * ------------------------------------------------------------------------ **
809    */
810   {
811   return( Neighbor( P, LEFT ) );
812   } /* ubi_btPrev */
813
814 ubi_btNodePtr ubi_btFirst( ubi_btNodePtr P )
815   /* ------------------------------------------------------------------------ **
816    * Given the node indicated by P, find the (sorted order) First node in the
817    * subtree of which *P is the root.
818    *  Input:   P  -  a pointer to a node that exists in a binary tree.
819    *  Output:  A pointer to the "first" node in a subtree that has *P as its
820    *           root.  This function will return NULL only if P is NULL.
821    *  Note:    In general, you will be passing in the value of the root field
822    *           of an ubi_btRoot structure.
823    * ------------------------------------------------------------------------ **
824    */
825   {
826   return( SubSlide( P, LEFT ) );
827   } /* ubi_btFirst */
828
829 ubi_btNodePtr ubi_btLast( ubi_btNodePtr P )
830   /* ------------------------------------------------------------------------ **
831    * Given the node indicated by P, find the (sorted order) Last node in the
832    * subtree of which *P is the root.
833    *  Input:   P  -  a pointer to a node that exists in a binary tree.
834    *  Output:  A pointer to the "last" node in a subtree that has *P as its
835    *           root.  This function will return NULL only if P is NULL.
836    *  Note:    In general, you will be passing in the value of the root field
837    *           of an ubi_btRoot structure.
838    * ------------------------------------------------------------------------ **
839    */
840   {
841   return( SubSlide( P, RIGHT ) );
842   } /* ubi_btLast */
843
844 ubi_btNodePtr ubi_btFirstOf( ubi_btRootPtr RootPtr,
845                              ubi_btItemPtr MatchMe,
846                              ubi_btNodePtr p )
847   /* ------------------------------------------------------------------------ **
848    * Given a tree that a allows duplicate keys, and a pointer to a node in
849    * the tree, this function will return a pointer to the first (traversal
850    * order) node with the same key value.
851    *
852    *  Input:  RootPtr - A pointer to the root of the tree.
853    *          MatchMe - A pointer to the key value.  This should probably
854    *                    point to the key within node *p.
855    *          p       - A pointer to a node in the tree.
856    *  Output: A pointer to the first node in the set of nodes with keys
857    *          matching <FindMe>.
858    *  Notes:  Node *p MUST be in the set of nodes with keys matching
859    *          <FindMe>.  If not, this function will return NULL.
860    * ------------------------------------------------------------------------ **
861    */
862   {
863   /* If our starting point is invalid, return NULL. */
864   if( !p || AbNormal( (*(RootPtr->cmp))( MatchMe, p ) != EQUAL ) )
865     return( NULL );
866   return( Border( RootPtr, MatchMe, p, LEFT ) );
867   } /* ubi_btFirstOf */
868
869 ubi_btNodePtr ubi_btLastOf( ubi_btRootPtr RootPtr,
870                             ubi_btItemPtr MatchMe,
871                             ubi_btNodePtr p )
872   /* ------------------------------------------------------------------------ **
873    * Given a tree that a allows duplicate keys, and a pointer to a node in
874    * the tree, this function will return a pointer to the last (traversal
875    * order) node with the same key value.
876    *
877    *  Input:  RootPtr - A pointer to the root of the tree.
878    *          MatchMe - A pointer to the key value.  This should probably
879    *                    point to the key within node *p.
880    *          p       - A pointer to a node in the tree.
881    *  Output: A pointer to the last node in the set of nodes with keys
882    *          matching <FindMe>.
883    *  Notes:  Node *p MUST be in the set of nodes with keys matching
884    *          <FindMe>.  If not, this function will return NULL.
885    * ------------------------------------------------------------------------ **
886    */
887   {
888   /* If our starting point is invalid, return NULL. */
889   if( !p || AbNormal( (*(RootPtr->cmp))( MatchMe, p ) != EQUAL ) )
890     return( NULL );
891   return( Border( RootPtr, MatchMe, p, RIGHT ) );
892   } /* ubi_btLastOf */
893
894 ubi_trBool ubi_btTraverse( ubi_btRootPtr   RootPtr,
895                            ubi_btActionRtn EachNode,
896                            void           *UserData )
897   /* ------------------------------------------------------------------------ **
898    * Traverse a tree in sorted order (non-recursively).  At each node, call
899    * (*EachNode)(), passing a pointer to the current node, and UserData as the
900    * second parameter.
901    *  Input:   RootPtr  -  a pointer to an ubi_btRoot structure that indicates
902    *                       the tree to be traversed.
903    *           EachNode -  a pointer to a function to be called at each node
904    *                       as the node is visited.
905    *           UserData -  a generic pointer that may point to anything that
906    *                       you choose.
907    *  Output:  A boolean value.  FALSE if the tree is empty, otherwise TRUE.
908    * ------------------------------------------------------------------------ **
909    */
910   {
911   ubi_btNodePtr p;
912
913   if( !(p = ubi_btFirst( RootPtr->root )) ) return( ubi_trFALSE );
914
915   while( p )
916     {
917     EachNode( p, UserData );
918     p = ubi_btNext( p );
919     }
920   return( ubi_trTRUE );
921   } /* ubi_btTraverse */
922
923 ubi_trBool ubi_btKillTree( ubi_btRootPtr     RootPtr,
924                            ubi_btKillNodeRtn FreeNode )
925   /* ------------------------------------------------------------------------ **
926    * Delete an entire tree (non-recursively) and reinitialize the ubi_btRoot
927    * structure.  Note that this function will return FALSE if either parameter
928    * is NULL.
929    *
930    *  Input:   RootPtr  -  a pointer to an ubi_btRoot structure that indicates
931    *                       the root of the tree to delete.
932    *           FreeNode -  a function that will be called for each node in the
933    *                       tree to deallocate the memory used by the node.
934    *
935    *  Output:  A boolean value.  FALSE if either input parameter was NULL, else
936    *           TRUE.
937    *
938    * ------------------------------------------------------------------------ **
939    */
940   {
941   ubi_btNodePtr p, q;
942
943   if( !(RootPtr) || !(FreeNode) )
944     return( ubi_trFALSE );
945
946   p = ubi_btFirst( RootPtr->root );
947   while( p )
948     {
949     q = p;
950     while( q->Link[RIGHT] )
951       q = SubSlide( q->Link[RIGHT], LEFT );
952     p = q->Link[PARENT];
953     if( p )
954       p->Link[ ((p->Link[LEFT] == q)?LEFT:RIGHT) ] = NULL;
955     FreeNode((void *)q);
956     }
957
958   (void)ubi_btInitTree( RootPtr,
959                         RootPtr->cmp,
960                         RootPtr->flags );
961   return( ubi_trTRUE );
962   } /* ubi_btKillTree */
963
964 ubi_btNodePtr ubi_btLeafNode( ubi_btNodePtr leader )
965   /* ------------------------------------------------------------------------ **
966    * Returns a pointer to a leaf node.
967    *
968    *  Input:  leader  - Pointer to a node at which to start the descent.
969    *
970    *  Output: A pointer to a leaf node selected in a somewhat arbitrary
971    *          manner.
972    *
973    *  Notes:  I wrote this function because I was using splay trees as a
974    *          database cache.  The cache had a maximum size on it, and I
975    *          needed a way of choosing a node to sacrifice if the cache
976    *          became full.  In a splay tree, less recently accessed nodes
977    *          tend toward the bottom of the tree, meaning that leaf nodes
978    *          are good candidates for removal.  (I really can't think of
979    *          any other reason to use this function.)
980    *        + In a simple binary tree or an AVL tree, the most recently
981    *          added nodes tend to be nearer the bottom, making this a *bad*
982    *          way to choose which node to remove from the cache.
983    *        + Randomizing the traversal order is probably a good idea.  You
984    *          can improve the randomization of leaf node selection by passing
985    *          in pointers to nodes other than the root node each time.  A
986    *          pointer to any node in the tree will do.  Of course, if you
987    *          pass a pointer to a leaf node you'll get the same thing back.
988    *
989    * ------------------------------------------------------------------------ **
990    */
991   {
992   ubi_btNodePtr follower = NULL;
993   int           whichway = LEFT;
994
995   while( NULL != leader )
996     {
997     follower = leader;
998     leader   = follower->Link[ whichway ];
999     if( NULL == leader )
1000       {
1001       whichway = RevWay( whichway );
1002       leader   = follower->Link[ whichway ];
1003       }
1004     }
1005
1006   return( follower );
1007   } /* ubi_btLeafNode */
1008
1009 int ubi_btModuleID( int size, char *list[] )
1010   /* ------------------------------------------------------------------------ **
1011    * Returns a set of strings that identify the module.
1012    *
1013    *  Input:  size  - The number of elements in the array <list>.
1014    *          list  - An array of pointers of type (char *).  This array
1015    *                  should, initially, be empty.  This function will fill
1016    *                  in the array with pointers to strings.
1017    *  Output: The number of elements of <list> that were used.  If this value
1018    *          is less than <size>, the values of the remaining elements are
1019    *          not guaranteed.
1020    *
1021    *  Notes:  Please keep in mind that the pointers returned indicate strings
1022    *          stored in static memory.  Don't free() them, don't write over
1023    *          them, etc.  Just read them.
1024    * ------------------------------------------------------------------------ **
1025    */
1026   {
1027   if( size > 0 )
1028     {
1029     list[0] = ModuleID;
1030     if( size > 1 )
1031       list[1] = NULL;
1032     return( 1 );
1033     }
1034   return( 0 );
1035   } /* ubi_btModuleID */
1036
1037
1038 /* ========================================================================== */