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