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