another balanced tree fix (vexi bug 90)
[org.ibex.core.git] / src / org / ibex / util / BalancedTree.java
1 // Copyright (C) 2003 Adam Megacz <adam@ibex.org> all rights reserved.
2 //
3 // You may modify, copy, and redistribute this code under the terms of
4 // the GNU Library Public License version 2.1, with the exception of
5 // the portion of clause 6a after the semicolon (aka the "obnoxious
6 // relink clause")
7
8 package org.ibex.util;
9
10 // FEATURE: private void intersection() { }
11 // FEATURE: private void union() { }
12 // FEATURE: private void subset() { }
13 // FEATURE: grow if we run out of slots
14
15 /** a weight-balanced tree with fake leaves */
16 public class BalancedTree {
17
18
19     // Instance Variables ///////////////////////////////////////////////////////////////////
20
21     private int root = 0;                         ///< the slot of the root element
22
23     private int cached_index = -1;
24     private int cached_slot = -1;
25
26     // Public API //////////////////////////////////////////////////////////////////////////
27
28     /** the number of elements in the tree */
29     public final int treeSize() {
30         synchronized(BalancedTree.class) {
31             return root == 0 ? 0 : size[root];
32         }
33     }
34
35     /** clamps index to [0..treeSize()] and inserts object o *before* the specified index */
36     public final void insertNode(int index, Object o) {
37         synchronized(BalancedTree.class) {
38         if(o == null) throw new Error("can't insert nulls in the balanced tree");
39         cached_slot = cached_index = -1;
40         if (index < 0) index = 0;
41         if (index > treeSize()) index = treeSize();
42         int arg = allocateSlot(o);
43         if (root != 0) {
44             insert(index, arg, root, 0, false, false);
45         } else {
46             root = arg;
47             left[arg] = right[arg] = parent[arg] = 0;
48             size[arg] = 1;
49         }
50         }
51     }
52
53     /** clamps index to [0..treeSize()-1] and replaces the object at that index with object o */
54     public final void replaceNode(int index, Object o) {
55         synchronized(BalancedTree.class) {
56         if(o == null) throw new Error("can't insert nulls in the balanced tree");
57         cached_slot = cached_index = -1;
58         if(root == 0) throw new Error("called replaceNode() on an empty tree");
59         if (index < 0) index = 0;
60         if (index >= treeSize()) index = treeSize() - 1;
61         int arg = allocateSlot(o);
62         insert(index, arg, root, 0, true, false);
63         }
64     }
65
66     /** returns the index of o; runs in O((log n)^2) time unless cache hit */
67     public final int indexNode(Object o) { 
68         synchronized(BalancedTree.class) {
69         if(o == null) return -1;
70         if (cached_slot != -1 && objects[cached_slot] == o) return cached_index;
71
72         int slot = getSlot(o);
73         if(slot == -1) return -1;
74         
75         int index = 0;
76         while(true) {
77             // everything to the left is before us so add that to the index
78             index += sizeof(left[slot]);
79             // we are before anything on the right
80             while(left[parent[slot]] == slot) slot = parent[slot];
81             // we end of the first node who isn't on the left, go to the node that has as its child
82             slot = parent[slot];
83             // if we just processed the root we're done
84             if(slot == 0) break;
85             // count the node we're currently on towards the index
86             index++;
87         }
88         return index;
89         }
90     }
91
92     /** returns the object at index; runs in O(log n) time unless cache hit */
93     public final Object getNode(int index) {
94         synchronized(BalancedTree.class) {
95         if (index == cached_index) return objects[cached_slot];
96
97         if (cached_index != -1) {
98             int distance = Math.abs(index - cached_index);
99             // if the in-order distance between the cached node and the
100             // target node is less than log(n), it's probably faster to
101             // search directly.
102             if ((distance < 16) && ((2 << distance) < treeSize())) {
103                 while(cached_index > index) { cached_slot = prev(cached_slot); cached_index--; }
104                 while(cached_index < index) { cached_slot = next(cached_slot); cached_index++; }
105                 return objects[cached_slot];
106             }
107         }
108         /*
109         cached_index = index;
110         cached_slot = get(index, root);
111         return objects[cached_slot];
112         */
113         return objects[get(index, root)];
114         }
115     }
116
117     /** deletes the object at index, returning the deleted object */
118     public final Object deleteNode(int index) {
119         synchronized(BalancedTree.class) {
120         cached_slot = cached_index = -1;
121         // FIXME: left[], right[], size[], and parent[] aren't getting cleared properly somewhere in here where a node had two children
122         int del = delete(index, root, 0);
123         left[del] = right[del] = size[del] = parent[del] = 0;
124         Object ret = objects[del];
125         objects[del] = null;
126         return ret;
127         }
128     }
129     
130     public final void clear() {
131         synchronized(BalancedTree.class) {
132         if(root == 0) return;
133         int i = leftmost(root);
134         do {
135             int next = next(i);
136             objects[i] = null;
137             left[i] = right[i] = size[i] = parent[i] = 0;
138             i = next;
139         } while(i != 0);
140         root = 0;
141         }
142     }
143     
144     protected void finalize() { clear(); }
145
146
147     // Node Data /////////////////////////////////////////////////////////////////////////
148
149     private final static int NUM_SLOTS = 64 * 1024;
150     // FEATURE: GROW - private final static int MAX_SLOT_DISTANCE = 32;
151
152     /**
153      * Every object inserted into *any* tree gets a "slot" in this
154      * array.  The slot is determined by hashcode modulo the length of
155      * the array, with quadradic probing to resolve collisions.  NOTE
156      * that the "slot" of a node is NOT the same as its index.
157      * Furthermore, if an object is inserted into multiple trees, that
158      * object will have multiple slots.
159      */
160     private static Object[] objects = new Object[NUM_SLOTS];
161
162     /// These two arrays hold the left and right children of each
163     /// slot; in other words, left[x] is the *slot* of the left child
164     /// of the node in slot x.
165     ///
166     /// If x has no left child, then left[x] is -1 multiplied by the
167     /// slot of the node that precedes x; if x is the first node, then
168     /// left[x] is 0.  The right[] array works the same way.
169     ///
170     private static int[] left = new int[NUM_SLOTS];
171     private static int[] right = new int[NUM_SLOTS];
172     
173     /// The parent of this node (0 if it is the root node)
174     private static int[] parent = new int[NUM_SLOTS];
175
176     ///< the number of descendants of this node *including the node itself*
177     private static int[] size = new int[NUM_SLOTS];
178
179
180     // Slot Management //////////////////////////////////////////////////////////////////////
181     
182     /** if alloc == false returns the slot holding object o. if alloc is true returns a new slot for obejct o */
183     private int getSlot(Object o, boolean alloc) {
184         // we XOR with our own hashcode so that we don't get tons of
185         // collisions when a single Object is inserted into multiple
186         // trees
187         int dest = Math.abs(o.hashCode() ^ this.hashCode()) % objects.length;
188         Object search = alloc ? null : o;
189         int odest = dest;
190         boolean plus = true;
191         int tries = 1;
192         if(dest == 0) dest=1;
193         while (objects[dest] != search || !(alloc || root(dest) == root)) {
194             dest = Math.abs((odest + (plus ? 1 : -1) * tries * tries) % objects.length);
195             if (dest == 0) dest=1;
196             if (plus) tries++;
197             plus = !plus;
198             // FEATURE: GROW - if(tries > MAX_SLOT_DISTANCE) return -1;
199         }
200         return dest;
201     }
202
203     /** returns the slots holding object o */
204     private int getSlot(Object o) { return getSlot(o,false); }
205     
206     /** allocates a new slot holding object o*/
207     private int allocateSlot(Object o) {
208         int slot = getSlot(o, true);
209         // FEATURE: GROW - if(slot == -1) throw new Error("out of slots");
210         objects[slot] = o;
211         return slot;
212     }
213
214
215
216     // Helpers /////////////////////////////////////////////////////////////////////////
217
218     private final int leftmost(int slot) { return left[slot] <= 0 ? slot : leftmost(left[slot]); }
219     private final int rightmost(int slot) { return right[slot] <= 0 ? slot : rightmost(right[slot]); }
220     private final int next(int slot) { return right[slot] <= 0 ? -1 * right[slot] : leftmost(right[slot]); }
221     private final int prev(int slot) { return left[slot] <= 0 ? -1 * left[slot] : rightmost(left[slot]); }
222     private final int sizeof(int slot) { return slot <= 0 ? 0 : size[slot]; }
223     private final int root(int slot) { return parent[slot] == 0 ? slot : root(parent[slot]); }
224
225
226     // Rotation and Balancing /////////////////////////////////////////////////////////////
227
228     //      p                  p
229     //      |                  |
230     //      b                  d 
231     //     / \                / \
232     //    a   d    < == >    b   e
233     //       / \            / \
234     //      c   e          a   c
235     // FIXME might be doing too much work here
236     private void rotate(boolean toTheLeft, int b, int p) {
237         int[] left = toTheLeft ? BalancedTree.left : BalancedTree.right;
238         int[] right = toTheLeft ? BalancedTree.right : BalancedTree.left;
239         int d = right[b];
240         int c = left[d];
241         if (d <= 0) throw new Error("rotation error");
242         left[d] = b;
243         right[b] = c <= 0 ? -d : c;
244         
245         parent[b] = d;
246         parent[d] = p;
247         if(c > 0) parent[c] = b;
248         if (p == 0)              root = d;
249         else if (left[p] == b)   left[p] = d;
250         else if (right[p] == b)  right[p] = d;
251         else throw new Error("rotate called with invalid parent");
252         size[b] = 1 + sizeof(left[b]) + sizeof(right[b]);
253         size[d] = 1 + sizeof(left[d]) + sizeof(right[d]);
254     }
255
256     private void balance(int slot, int p) {
257         if (slot <= 0) return;
258         size[slot] = 1 + sizeof(left[slot]) + sizeof(right[slot]);
259         if (sizeof(left[slot]) - 1 > 2 * sizeof(right[slot])) rotate(false, slot, p);
260         else if (sizeof(left[slot]) * 2 < sizeof(right[slot]) - 1) rotate(true, slot, p);
261     }
262
263
264
265     // Insert /////////////////////////////////////////////////////////////////////////
266
267     private void insert(int index, int arg, int slot, int p, boolean replace, boolean wentLeft) {
268         int diff = slot <= 0 ? 0 : index - sizeof(left[slot]);
269         if (slot > 0 && diff != 0) {
270             if (diff < 0) insert(index, arg, left[slot], slot, replace, true);
271             else insert(index - sizeof(left[slot]) - 1, arg, right[slot], slot, replace, false);
272             balance(slot, p);
273             return;
274         }
275
276         if (size[arg] != 0) throw new Error("double insertion");
277
278         // we are replacing an existing node
279         if (replace) {
280             if (diff != 0) throw new Error("this should never happen"); // since we already clamped the index
281             if (p == 0)                 root = arg;
282             else if (left[p] == slot)   left[p] = arg;
283             else if (right[p] == slot)  right[p] = arg;
284             left[arg] = left[slot];
285             right[arg] = right[slot];
286             size[arg] = size[slot];
287             parent[arg] = parent[slot];
288             if(left[slot] > 0) parent[left[slot]] = arg;
289             if(right[slot] > 0) parent[right[slot]] = arg;
290             objects[slot] = null;
291             left[slot] = right[slot] = size[slot] = parent[slot] = 0;
292         
293         // we become the child of a former leaf
294         } else if (slot <= 0) {
295             int[] left = wentLeft ? BalancedTree.left : BalancedTree.right;
296             int[] right = wentLeft ? BalancedTree.right : BalancedTree.left;
297             left[arg] = slot;
298             left[p] = arg;
299             right[arg] = -1 * p;
300             parent[arg] = p;
301             balance(arg, p);
302
303         // we take the place of a preexisting node
304         } else {
305             left[arg] = left[slot];   // steal slot's left subtree
306             left[slot] = -1 * arg;
307             right[arg] = slot;        // make slot our right subtree
308             parent[arg] = parent[slot];
309             parent[slot] = arg;
310             if (slot == root) {
311                 root = arg;
312                 balance(slot, arg);
313                 balance(arg, 0);
314             } else {
315                 if (left[p] == slot)        left[p] = arg;
316                 else if (right[p] == slot)  right[p] = arg;
317                 else throw new Error("should never happen");
318                 balance(slot, arg);
319                 balance(arg, p);
320             }
321         }
322     }
323
324
325     // Retrieval //////////////////////////////////////////////////////////////////////
326
327     private int get(int index, int slot) {
328         int diff = index - sizeof(left[slot]);
329         if (diff > 0) return get(diff - 1, right[slot]);
330         else if (diff < 0) return get(index, left[slot]);
331         else return slot;
332     }
333
334
335     // Deletion //////////////////////////////////////////////////////////////////////
336
337     private int delete(int index, int slot, int p) {
338         int diff = index - sizeof(left[slot]);
339         if (diff < 0) {
340             int ret = delete(index, left[slot], slot);
341             balance(slot, p);
342             return ret;
343
344         } else if (diff > 0) {
345             int ret = delete(diff - 1, right[slot], slot);
346             balance(slot, p);
347             return ret;
348
349         // we found the node to delete
350         } else {
351
352             // fast path: it has no children
353             if (left[slot] <= 0 && right[slot] <= 0) {
354                 if (p == 0) root = 0;
355                 else {
356                     int[] side = left[p] == slot ? left : right;
357                     side[p] = side[slot];      // fix parent's pointer
358                 }
359                 
360             // fast path: it has no left child, so we replace it with its right child
361             } else if (left[slot] <= 0) {
362                 if (p == 0) root = right[slot];
363                 else (left[p] == slot ? left : right)[p] = right[slot];     // fix parent's pointer
364                 parent[right[slot]] = p;
365                 left[leftmost(right[slot])] = left[slot];                             // fix our successor-leaf's fake right ptr
366                 balance(right[slot], p);
367
368             // fast path; it has no right child, so we replace it with its left child
369             } else if (right[slot] <= 0) {
370                 if (p == 0) root = left[slot];
371                 else (left[p] == slot ? left : right)[p] = left[slot];      // fix parent's pointer
372                 parent[left[slot]] = p;
373                 right[rightmost(left[slot])] = right[slot];                           // fix our successor-leaf's fake right ptr
374                 balance(left[slot], p);
375
376             // node to be deleted has two children, so we replace it with its left child's rightmost descendant
377             } else {
378                 int left_childs_rightmost = delete(sizeof(left[slot]) - 1, left[slot], slot);
379                 left[left_childs_rightmost] = left[slot];
380                 right[left_childs_rightmost] = right[slot];
381                 if(left[slot] > 0) parent[left[slot]] = left_childs_rightmost;
382                 if(right[slot] > 0) parent[right[slot]] = left_childs_rightmost;
383                 parent[left_childs_rightmost] = parent[slot];
384                 if (p == 0) root = left_childs_rightmost;
385                 else (left[p] == slot ? left : right)[p] = left_childs_rightmost;     // fix parent's pointer
386                 balance(left_childs_rightmost, p);
387             }
388
389             return slot;
390         }
391     }
392
393     // Debugging ///////////////////////////////////////////////////////////////////////////
394     
395     public void printTree() {
396         if(root == 0) System.err.println("Tree is empty");
397         else printTree(root,0,false);
398     }
399     private void printTree(int node,int indent,boolean l) {
400         for(int i=0;i<indent;i++) System.err.print("   ");
401         if(node < 0) System.err.println((l?"Prev: " : "Next: ") + -node);
402         else if(node == 0)  System.err.println(l ? "Start" : "End");
403         else {
404             System.err.print("" + node + ": " + objects[node]);
405             System.err.println(" Parent: " + parent[node]);
406             printTree(left[node],indent+1,true);
407             printTree(right[node],indent+1,false);
408         }
409     }
410 }