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