version incremented
[samba] / source / ubiqx / ubi_SplayTree.c
1 /* ========================================================================== **
2  *                              ubi_SplayTree.c
3  *
4  *  Copyright (C) 1993-1998 by Christopher R. Hertel
5  *
6  *  Email: crh@ubiqx.mn.org
7  * -------------------------------------------------------------------------- **
8  *
9  *  This module implements "splay" trees.  Splay trees are binary trees
10  *  that are rearranged (splayed) whenever a node is accessed.  The
11  *  splaying process *tends* to make the tree bushier (improves balance),
12  *  and the nodes that are accessed most frequently *tend* to be closer to
13  *  the top.
14  *
15  *  References: "Self-Adjusting Binary Search Trees", by Daniel Sleator and
16  *              Robert Tarjan.  Journal of the Association for Computing
17  *              Machinery Vol 32, No. 3, July 1985 pp. 652-686
18  *
19  *    See also: http://www.cs.cmu.edu/~sleator/
20  *
21  * -------------------------------------------------------------------------- **
22  *
23  *  This library is free software; you can redistribute it and/or
24  *  modify it under the terms of the GNU Library General Public
25  *  License as published by the Free Software Foundation; either
26  *  version 2 of the License, or (at your option) any later version.
27  *
28  *  This library is distributed in the hope that it will be useful,
29  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
30  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
31  *  Library General Public License for more details.
32  *
33  *  You should have received a copy of the GNU Library General Public
34  *  License along with this library; if not, write to the Free
35  *  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
36  *
37  * -------------------------------------------------------------------------- **
38  *
39  * Log: ubi_SplayTree.c,v 
40  * Revision 4.5  2000/01/08 23:26:49  crh
41  * Added ubi_trSplay() macro, which does a type cast for us.
42  *
43  * Revision 4.4  1998/06/04 21:29:27  crh
44  * Upper-cased defined constants (eg UBI_BINTREE_H) in some header files.
45  * This is more "standard", and is what people expect.  Weird, eh?
46  *
47  * Revision 4.3  1998/06/03 17:45:05  crh
48  * Further fiddling with sys_include.h.  It's now in ubi_BinTree.h which is
49  * included by all of the binary tree files.
50  *
51  * Also fixed some warnings produced by lint on Irix 6.2, which doesn't seem
52  * to like syntax like this:
53  *
54  *   if( (a = b) )
55  *
56  * The fix was to change lines like the above to:
57  *
58  *   if( 0 != (a=b) )
59  *
60  * Which means the same thing.
61  *
62  * Reminder: Some of the ubi_tr* macros in ubi_BinTree.h are redefined in
63  *           ubi_AVLtree.h and ubi_SplayTree.h.  This allows easy swapping
64  *           of tree types by simply changing a header.  Unfortunately, the
65  *           macro redefinitions in ubi_AVLtree.h and ubi_SplayTree.h will
66  *           conflict if used together.  You must either choose a single tree
67  *           type, or use the underlying function calls directly.  Compare
68  *           the two header files for more information.
69  *
70  * Revision 4.2  1998/06/02 01:29:14  crh
71  * Changed ubi_null.h to sys_include.h to make it more generic.
72  *
73  * Revision 4.1  1998/05/20 04:37:54  crh
74  * The C file now includes ubi_null.h.  See ubi_null.h for more info.
75  *
76  * Revision 4.0  1998/03/10 03:41:33  crh
77  * Minor comment changes.  The revision number is now 4.0 to match the
78  * BinTree and AVLtree modules.
79  *
80  * Revision 2.7  1998/01/24 06:37:08  crh
81  * Added a URL for more information.
82  *
83  * Revision 2.6  1997/12/23 04:01:12  crh
84  * In this version, all constants & macros defined in the header file have
85  * the ubi_tr prefix.  Also cleaned up anything that gcc complained about
86  * when run with '-pedantic -fsyntax-only -Wall'.
87  *
88  * Revision 2.5  1997/07/26 04:15:42  crh
89  * + Cleaned up a few minor syntax annoyances that gcc discovered for me.
90  * + Changed ubi_TRUE and ubi_FALSE to ubi_trTRUE and ubi_trFALSE.
91  *
92  * Revision 2.4  1997/06/03 04:42:21  crh
93  * Changed TRUE and FALSE to ubi_TRUE and ubi_FALSE to avoid causing
94  * problems.
95  *
96  * Revision 2.3  1995/10/03 22:19:07  CRH
97  * Ubisized!
98  * Also, added the function ubi_sptSplay().
99  *
100  * Revision 2.1  95/03/09  23:54:42  CRH
101  * Added the ModuleID static string and function.  These modules are now
102  * self-identifying.
103  * 
104  * Revision 2.0  95/02/27  22:34:46  CRH
105  * This module was updated to match the interface changes made to the
106  * ubi_BinTree module.  In particular, the interface to the Locate() function
107  * has changed.  See ubi_BinTree for more information on changes and new
108  * functions.
109  *
110  * The revision number was also upped to match ubi_BinTree.
111  *
112  * Revision 1.1  93/10/18  20:35:16  CRH
113  * I removed the hard-coded logical device names from the include file
114  * specifications.  CRH
115  *
116  * Revision 1.0  93/10/15  23:00:15  CRH
117  * With this revision, I have added a set of #define's that provide a single,
118  * standard API to all existing tree modules.  Until now, each of the three
119  * existing modules had a different function and typedef prefix, as follows:
120  *
121  *       Module        Prefix
122  *     ubi_BinTree     ubi_bt
123  *     ubi_AVLtree     ubi_avl
124  *     ubi_SplayTree   ubi_spt
125  *
126  * To further complicate matters, only those portions of the base module
127  * (ubi_BinTree) that were superceeded in the new module had the new names.
128  * For example, if you were using ubi_SplayTree, the locate function was
129  * called "ubi_sptLocate", but the next and previous functions remained
130  * "ubi_btNext" and "ubi_btPrev".
131  *
132  * This was not too terrible if you were familiar with the modules and knew
133  * exactly which tree model you wanted to use.  If you wanted to be able to
134  * change modules (for speed comparisons, etc), things could get messy very
135  * quickly.
136  *
137  * So, I have added a set of defined names that get redefined in any of the
138  * descendant modules.  To use this standardized interface in your code,
139  * simply replace all occurances of "ubi_bt", "ubi_avl", and "ubi_spt" with
140  * "ubi_tr".  The "ubi_tr" names will resolve to the correct function or
141  * datatype names for the module that you are using.  Just remember to
142  * include the header for that module in your program file.  Because these
143  * names are handled by the preprocessor, there is no added run-time
144  * overhead.
145  *
146  * Note that the original names do still exist, and can be used if you wish
147  * to write code directly to a specific module.  This should probably only be
148  * done if you are planning to implement a new descendant type, such as
149  * red/black trees.  CRH
150  *
151  * Revision 0.1  93/04/25  22:03:32  CRH
152  * Simply changed the <exec/types.h> #include reference the .c file to
153  * use <stdlib.h> instead.  The latter is portable, the former is not.
154  *
155  * Revision 0.0  93/04/21  23:05:52  CRH
156  * Initial version, written by Christopher R. Hertel.
157  * This module implements Splay Trees using the ubi_BinTree module as a basis.
158  *
159  * ========================================================================== **
160  */
161
162 #include "ubi_SplayTree.h"  /* Header for THIS module.   */
163
164 /* ========================================================================== **
165  * Static data.
166  */
167
168 static char ModuleID[] = "ubi_SplayTree\n\
169 \tRevision: 4.5 \n\
170 \tDate: 2000/01/08 23:26:49 \n\
171 \tAuthor: crh \n";
172
173
174 /* ========================================================================== **
175  * Private functions...
176  */
177
178 static void Rotate( ubi_btNodePtr p )
179   /* ------------------------------------------------------------------------ **
180    * This function performs a single rotation, moving node *p up one level
181    * in the tree.
182    *
183    *  Input:    p - a pointer to an ubi_btNode in a tree.
184    *
185    *  Output:   None.
186    *
187    *  Notes:    This implements a single rotation in either direction (left
188    *            or right).  This is the basic building block of all splay
189    *            tree rotations.
190    * ------------------------------------------------------------------------ **
191    */
192   {
193   ubi_btNodePtr parentp;
194   ubi_btNodePtr tmp;
195   char          way;
196   char          revway;
197
198   parentp = p->Link[ubi_trPARENT];    /* Find parent. */
199
200   if( parentp )                 /* If no parent, then we're already the root. */
201     {
202     way    = p->gender;
203     revway = ubi_trRevWay(way);
204     tmp    = p->Link[(int)revway];
205
206     parentp->Link[(int)way] = tmp;
207     if( tmp )
208       {
209       tmp->Link[ubi_trPARENT] = parentp;
210       tmp->gender             = way;
211       }
212
213     tmp                   = parentp->Link[ubi_trPARENT];
214     p->Link[ubi_trPARENT] = tmp;
215     p->gender             = parentp->gender;
216     if( tmp )
217       tmp->Link[(int)(p->gender)] = p;
218
219     parentp->Link[ubi_trPARENT] = p;
220     parentp->gender             = revway;
221     p->Link[(int)revway]        = parentp;
222     }
223   } /* Rotate */
224
225 static ubi_btNodePtr Splay( ubi_btNodePtr SplayWithMe )
226   /* ------------------------------------------------------------------------ **
227    * Move the node indicated by SplayWithMe to the root of the tree by
228    * splaying the tree.
229    *
230    *  Input:  SplayWithMe - A pointer to an ubi_btNode within a tree.
231    *
232    *  Output: A pointer to the root of the splay tree (i.e., the same as
233    *          SplayWithMe).
234    * ------------------------------------------------------------------------ **
235    */
236   {
237   ubi_btNodePtr parent;
238
239   while( NULL != (parent = SplayWithMe->Link[ubi_trPARENT]) )
240     {
241     if( parent->gender == SplayWithMe->gender )       /* Zig-Zig */
242       Rotate( parent );
243     else
244       {
245       if( ubi_trEQUAL != parent->gender )             /* Zig-Zag */
246         Rotate( SplayWithMe );
247       }
248     Rotate( SplayWithMe );                            /* Zig */
249     } /* while */
250   return( SplayWithMe );
251   } /* Splay */
252
253 /* ========================================================================== **
254  * Exported utilities.
255  */
256
257 ubi_trBool ubi_sptInsert( ubi_btRootPtr  RootPtr,
258                           ubi_btNodePtr  NewNode,
259                           ubi_btItemPtr  ItemPtr,
260                           ubi_btNodePtr *OldNode )
261   /* ------------------------------------------------------------------------ **
262    * This function uses a non-recursive algorithm to add a new element to the
263    * splay tree.
264    *
265    *  Input:   RootPtr  -  a pointer to the ubi_btRoot structure that indicates
266    *                       the root of the tree to which NewNode is to be added.
267    *           NewNode  -  a pointer to an ubi_btNode structure that is NOT
268    *                       part of any tree.
269    *           ItemPtr  -  A pointer to the sort key that is stored within
270    *                       *NewNode.  ItemPtr MUST point to information stored
271    *                       in *NewNode or an EXACT DUPLICATE.  The key data
272    *                       indicated by ItemPtr is used to place the new node
273    *                       into the tree.
274    *           OldNode  -  a pointer to an ubi_btNodePtr.  When searching
275    *                       the tree, a duplicate node may be found.  If
276    *                       duplicates are allowed, then the new node will
277    *                       be simply placed into the tree.  If duplicates
278    *                       are not allowed, however, then one of two things
279    *                       may happen.
280    *                       1) if overwritting *is not* allowed, this
281    *                          function will return FALSE (indicating that
282    *                          the new node could not be inserted), and
283    *                          *OldNode will point to the duplicate that is
284    *                          still in the tree.
285    *                       2) if overwritting *is* allowed, then this
286    *                          function will swap **OldNode for *NewNode.
287    *                          In this case, *OldNode will point to the node
288    *                          that was removed (thus allowing you to free
289    *                          the node).
290    *                          **  If you are using overwrite mode, ALWAYS  **
291    *                          ** check the return value of this parameter! **
292    *                 Note: You may pass NULL in this parameter, the
293    *                       function knows how to cope.  If you do this,
294    *                       however, there will be no way to return a
295    *                       pointer to an old (ie. replaced) node (which is
296    *                       a problem if you are using overwrite mode).
297    *
298    *  Output:  a boolean value indicating success or failure.  The function
299    *           will return FALSE if the node could not be added to the tree.
300    *           Such failure will only occur if duplicates are not allowed,
301    *           nodes cannot be overwritten, AND a duplicate key was found
302    *           within the tree.
303    * ------------------------------------------------------------------------ **
304    */
305   {
306   ubi_btNodePtr OtherP;
307
308   if( !(OldNode) )
309     OldNode = &OtherP;
310
311   if( ubi_btInsert( RootPtr, NewNode, ItemPtr, OldNode ) )
312     {
313     RootPtr->root = Splay( NewNode );
314     return( ubi_trTRUE );
315     }
316
317   /* Splay the unreplacable, duplicate keyed, unique, old node. */
318   RootPtr->root = Splay( (*OldNode) );
319   return( ubi_trFALSE );
320   } /* ubi_sptInsert */
321
322 ubi_btNodePtr ubi_sptRemove( ubi_btRootPtr RootPtr, ubi_btNodePtr DeadNode )
323   /* ------------------------------------------------------------------------ **
324    * This function removes the indicated node from the tree.
325    *
326    *  Input:   RootPtr  -  A pointer to the header of the tree that contains
327    *                       the node to be removed.
328    *           DeadNode -  A pointer to the node that will be removed.
329    *
330    *  Output:  This function returns a pointer to the node that was removed
331    *           from the tree (ie. the same as DeadNode).
332    *
333    *  Note:    The node MUST be in the tree indicated by RootPtr.  If not,
334    *           strange and evil things will happen to your trees.
335    * ------------------------------------------------------------------------ **
336    */
337   {
338   ubi_btNodePtr p;
339
340   (void)Splay( DeadNode );                  /* Move dead node to root.        */
341   if( NULL != (p = DeadNode->Link[ubi_trLEFT]) )
342     {                                       /* If left subtree exists...      */
343     ubi_btNodePtr q = DeadNode->Link[ubi_trRIGHT];
344
345     p->Link[ubi_trPARENT] = NULL;           /* Left subtree node becomes root.*/
346     p->gender             = ubi_trPARENT;
347     p                     = ubi_btLast( p );  /* Find rightmost left node...  */
348     p->Link[ubi_trRIGHT]  = q;                /* ...attach right tree.        */
349     if( q )
350       q->Link[ubi_trPARENT] = p;
351     RootPtr->root   = Splay( p );           /* Resplay at p.                  */
352     }
353   else
354     {
355     if( NULL != (p = DeadNode->Link[ubi_trRIGHT]) )
356       {                               /* No left, but right subtree exists... */
357       p->Link[ubi_trPARENT] = NULL;         /* Right subtree root becomes...  */
358       p->gender       = ubi_trPARENT;       /* ...overall tree root.          */
359       RootPtr->root   = p;
360       }
361     else
362       RootPtr->root = NULL;                 /* No subtrees => empty tree.     */
363     }
364
365   (RootPtr->count)--;                       /* Decrement node count.          */
366   return( DeadNode );                       /* Return pointer to pruned node. */
367   } /* ubi_sptRemove */
368
369 ubi_btNodePtr ubi_sptLocate( ubi_btRootPtr RootPtr,
370                              ubi_btItemPtr FindMe,
371                              ubi_trCompOps CompOp )
372   /* ------------------------------------------------------------------------ **
373    * The purpose of ubi_btLocate() is to find a node or set of nodes given
374    * a target value and a "comparison operator".  The Locate() function is
375    * more flexible and (in the case of trees that may contain dupicate keys)
376    * more precise than the ubi_btFind() function.  The latter is faster,
377    * but it only searches for exact matches and, if the tree contains
378    * duplicates, Find() may return a pointer to any one of the duplicate-
379    * keyed records.
380    *
381    *  Input:
382    *     RootPtr  -  A pointer to the header of the tree to be searched.
383    *     FindMe   -  An ubi_btItemPtr that indicates the key for which to
384    *                 search.
385    *     CompOp   -  One of the following:
386    *                    CompOp     Return a pointer to the node with
387    *                    ------     ---------------------------------
388    *                   ubi_trLT - the last key value that is less
389    *                              than FindMe.
390    *                   ubi_trLE - the first key matching FindMe, or
391    *                              the last key that is less than
392    *                              FindMe.
393    *                   ubi_trEQ - the first key matching FindMe.
394    *                   ubi_trGE - the first key matching FindMe, or the
395    *                              first key greater than FindMe.
396    *                   ubi_trGT - the first key greater than FindMe.
397    *  Output:
398    *     A pointer to the node matching the criteria listed above under
399    *     CompOp, or NULL if no node matched the criteria.
400    *
401    *  Notes:
402    *     In the case of trees with duplicate keys, Locate() will behave as
403    *     follows:
404    *
405    *     Find:  3                       Find: 3
406    *     Keys:  1 2 2 2 3 3 3 3 3 4 4   Keys: 1 1 2 2 2 4 4 5 5 5 6
407    *                  ^ ^         ^                   ^ ^
408    *                 LT EQ        GT                 LE GE
409    *
410    *     That is, when returning a pointer to a node with a key that is LESS
411    *     THAN the target key (FindMe), Locate() will return a pointer to the
412    *     LAST matching node.
413    *     When returning a pointer to a node with a key that is GREATER
414    *     THAN the target key (FindMe), Locate() will return a pointer to the
415    *     FIRST matching node.
416    *
417    *  See Also: ubi_btFind(), ubi_btFirstOf(), ubi_btLastOf().
418    * ------------------------------------------------------------------------ **
419    */
420   {
421   ubi_btNodePtr p;
422
423   p = ubi_btLocate( RootPtr, FindMe, CompOp );
424   if( p )
425     RootPtr->root = Splay( p );
426   return( p );
427   } /* ubi_sptLocate */
428
429 ubi_btNodePtr ubi_sptFind( ubi_btRootPtr RootPtr,
430                            ubi_btItemPtr FindMe )
431   /* ------------------------------------------------------------------------ **
432    * This function performs a non-recursive search of a tree for any node
433    * matching a specific key.
434    *
435    *  Input:
436    *     RootPtr  -  a pointer to the header of the tree to be searched.
437    *     FindMe   -  a pointer to the key value for which to search.
438    *
439    *  Output:
440    *     A pointer to a node with a key that matches the key indicated by
441    *     FindMe, or NULL if no such node was found.
442    *
443    *  Note:   In a tree that allows duplicates, the pointer returned *might
444    *          not* point to the (sequentially) first occurance of the
445    *          desired key.  In such a tree, it may be more useful to use
446    *          ubi_sptLocate().
447    * ------------------------------------------------------------------------ **
448    */
449   {
450   ubi_btNodePtr p;
451
452   p = ubi_btFind( RootPtr, FindMe );
453   if( p )
454     RootPtr->root = Splay( p );
455   return( p );
456   } /* ubi_sptFind */
457
458 void ubi_sptSplay( ubi_btRootPtr RootPtr,
459                    ubi_btNodePtr SplayMe )
460   /* ------------------------------------------------------------------------ **
461    *  This function allows you to splay the tree at a given node, thus moving
462    *  the node to the top of the tree.
463    *
464    *  Input:
465    *     RootPtr  -  a pointer to the header of the tree to be splayed.
466    *     SplayMe  -  a pointer to a node within the tree.  This will become
467    *                 the new root node.
468    *  Output: None.
469    *
470    *  Notes:  This is an uncharacteristic function for this group of modules
471    *          in that it provides access to the internal balancing routines,
472    *          which would normally be hidden.
473    *          Splaying the tree will not damage it (assuming that I've done
474    *          *my* job), but there is overhead involved.  I don't recommend
475    *          that you use this function unless you understand the underlying
476    *          Splay Tree principles involved.
477    * ------------------------------------------------------------------------ **
478    */
479   {
480   RootPtr->root = Splay( SplayMe );
481   } /* ubi_sptSplay */
482
483 int ubi_sptModuleID( int size, char *list[] )
484   /* ------------------------------------------------------------------------ **
485    * Returns a set of strings that identify the module.
486    *
487    *  Input:  size  - The number of elements in the array <list>.
488    *          list  - An array of pointers of type (char *).  This array
489    *                  should, initially, be empty.  This function will fill
490    *                  in the array with pointers to strings.
491    *  Output: The number of elements of <list> that were used.  If this value
492    *          is less than <size>, the values of the remaining elements are
493    *          not guaranteed.
494    *
495    *  Notes:  Please keep in mind that the pointers returned indicate strings
496    *          stored in static memory.  Don't free() them, don't write over
497    *          them, etc.  Just read them.
498    * ------------------------------------------------------------------------ **
499    */
500   {
501   if( size > 0 )
502     {
503     list[0] = ModuleID;
504     if( size > 1 )
505       return( 1 + ubi_btModuleID( --size, &(list[1]) ) );
506     return( 1 );
507     }
508   return( 0 );
509   } /* ubi_sptModuleID */
510
511 /* ================================ The End ================================= */
512