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