Hash->HashMap, add Basket.Queue
[org.ibex.util.git] / src / org / ibex / util / Basket.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.util;
6
7 import java.io.Serializable;
8
9 public interface Basket extends Serializable {
10     public boolean containsValue(Object object);
11     public void clear();
12     public int size();
13     public void remove(Object object);
14
15     public interface List extends Basket {
16         public void add(Object object);
17         public void add(int index, Object object);
18         public Object set(int index, Object object);
19         public Object get(int index);
20         public Object remove(int index);
21         public int indexOf(Object object);
22         public void reverse();
23         public void sort(CompareFunc c);
24     }
25
26     public interface RandomAccess extends List { }
27
28     public interface Queue extends Basket {
29         public void   enqueue(Object o);
30         public Object dequeue();
31     }
32
33     public interface Stack extends Basket {
34         public Object pop();
35         public Object peek();
36         public void push(Object object);
37     }
38
39     public interface Map extends Basket {
40         public boolean containsKey(Object key);
41         public Object get(Object key);
42         public Object put(Object key, Object value);
43     }
44
45     public interface CompareFunc {
46         public int compare(Object a, Object b);
47     }
48
49
50     // Implementations ////////////////////////////////////////////////////////
51
52     public class Array implements RandomAccess, Stack, Queue {
53         private static final long serialVersionUID = 1233428092L;
54
55         private Object[] o;
56         private int size = 0;
57
58         public Array() { this(10); }
59         public Array(int initialCapacity) { o = new Object[initialCapacity]; }
60         public Array(Object entry) { this(1); add(entry); }
61
62         public void   enqueue(Object o) { add(o); }
63
64         // FEATURE: make this more efficient with general wraparound
65         public Object dequeue() {
66             if (size==0) return null;
67             Object ret = o[0];
68             for(int i=1; i<size; i++) o[i-1]=o[i];
69             return ret;
70         }
71
72         public void add(Object obj) { add(size, obj); }
73         public void add(int i, Object obj) {
74             size(size + 1);
75             if (size - 1 > i) System.arraycopy(o, i, o, size, size - i - 1);
76             o[i] = obj; size++;
77         }
78         public Object set(int i, Object obj) {
79             if (i >= size) throw new IndexOutOfBoundsException(
80                 "index "+i+" is beyond list boundary "+size);
81             Object old = o[i]; o[i] = obj; return old;
82         }
83         public Object get(int i) {
84             if (i >= size) throw new IndexOutOfBoundsException(
85                 "index "+i+" is beyond list boundary "+size);
86             return o[i];
87         }
88         public Object remove(int i) {
89             if (i >= size || i < 0) throw new IndexOutOfBoundsException(
90                 "index "+i+" is beyond list boundary "+size);
91             Object old = o[i]; o[i] = null;
92             if (size - 1 > i) System.arraycopy(o, i + 1, o, i, size - i - 1);
93             size--; return old;
94         }
95         public void remove(Object obj) { remove(indexOf(obj)); }
96
97         public int indexOf(Object obj) {
98             for (int i=0; i < size; i++)
99                 if ((obj == null && o[i] == null) || obj.equals(o[i])) return i;
100             return -1;
101         }
102
103         public boolean containsValue(Object obj) {
104             for (int i=0; i < size; i++)
105                 if ((obj == null && o[i] == null) || obj.equals(o[i])) return true;
106             return false;
107         }
108         public void clear() { for (int i=0; i < size; i++) o[i] = null; size = 0; }
109         public int size() { return size; }
110         public void size(int s) {
111             if (o.length >= s) return;
112             Object[] newo = new Object[s];
113             System.arraycopy(o, 0, newo, 0, size);
114             o = newo;
115         }
116
117         public void reverse() {
118             Object tmp; int max = (int)Math.floor((double)size / 2);
119             for (int i=0; i < size; i++) { tmp = o[i]; o[i] = o[size - i]; o[size - i] = tmp; }
120         }
121
122         public void sort(CompareFunc c) { sort(this, null, c, 0, size); }
123
124         public static void sort(Array a, Array b, CompareFunc c, int start, int end) {
125             Object tmpa, tmpb = null;
126             if(start >= end) return;
127             if(end-start <= 6) {
128                 for(int i=start+1;i<=end;i++) {
129                     tmpa = a.o[i];
130                     if (b != null) tmpb = b.o[i];
131                     int j;
132                     for(j=i-1;j>=start;j--) {
133                         if(c.compare(a.o[j],tmpa) <= 0) break;
134                         a.o[j+1] = a.o[j];
135                         if (b != null) b.o[j+1] = b.o[j];
136                     }
137                     a.o[j+1] = tmpa;
138                     if (b != null) b.o[j+1] = tmpb;
139                 }
140                 return;
141             }
142             Object pivot = a.o[end];
143             int lo = start - 1;
144             int hi = end;
145             do {
146                 while(c.compare(a.o[++lo],pivot) < 0) { }
147                 while((hi > lo) && c.compare(a.o[--hi],pivot) > 0) { }
148                 swap(a, lo,hi);
149                 if (b != null) swap(b, lo,hi);
150             } while(lo < hi);
151
152             swap(a, lo,end);
153             if (b != null) swap(b, lo,end);
154             sort(a, b, c, start, lo-1);
155             sort(a, b, c, lo+1, end);
156         }
157
158         private static final void swap(Array vec, int a, int b) {
159             if(a != b) {
160                 Object tmp = vec.o[a];
161                 vec.o[a] = vec.o[b];
162                 vec.o[b] = tmp;
163             }
164         }
165
166         public Object peek() {
167             if (size < 1) throw new IndexOutOfBoundsException("array is empty");
168             return o[size - 1];
169         }
170         public Object pop() { return remove(size - 1); }
171         public void push(Object o) { add(o); }
172     }
173
174     /** Implementation of a hash table using Radke's quadratic residue
175      *  linear probing. Uses a single array to store all entries.
176      *
177      * <p>See C. Radke, Communications of the ACM, 1970, 103-105</p>
178      *
179      * @author adam@ibex.org, crawshaw@ibex.org
180      */
181     public class Hash implements Basket, Map {
182         static final long serialVersionUID = 3948384093L;
183
184         /** Used internally to record used slots. */
185         final Object placeholder = new java.io.Serializable() { private static final long serialVersionUID = 1331L; };
186
187         /** When <tt>loadFactor * usedslots > num_slots</tt>, call
188          *  <tt>rehash()</tt>. */
189         final float loadFactor;
190
191         /** Used to determine the number of array slots required by each
192          *  mapping entry. */
193         final int indexmultiple;
194
195         /** Number of currently active entries. */
196         private int size = 0;
197
198         /** Number of placeholders in entries[]. */
199         private int placeholders = 0;
200
201         /** Array of mappings.
202          *
203          *  <p>Each map requires multiple slots in the array, and subclasses
204          *  can vary the number of required slots without reimplementing all
205          *  the functions of this class by changing the value of
206          *  <tt>indexmultiple</tt>.</p>
207          *
208          *  Default implementation uses <tt>indexmultiple == 1</tt>, and
209          *  stores only the keys in <tt>entries</tt>.
210          */
211         private Object[] entries = null;
212
213         public Hash() { this(16, 0.75F); }
214         public Hash(int cap, float load) { this(2, cap, load); }
215         public Hash(int indexmultiple, int initialCapacity, float loadFactor) {
216             // using a pseudoprime in the form 4x+3 ensures full coverage
217             initialCapacity = (initialCapacity / 4) * 4 + 3;
218             this.loadFactor = loadFactor;
219             this.indexmultiple = indexmultiple;
220             this.entries = new Object[initialCapacity * indexmultiple];
221         }
222
223         public int size() { return size; }
224         public void clear() { for (int i = 0; i<entries.length; i++) entries[i] = null; size = 0; }
225
226         public boolean containsKey(Object k) { return indexOf(k) >= 0; }
227
228         /** <b>Warning:</b> This function is equivalent here to
229          *  <tt>containsKey()</tt>. For a value map, use Basket.HashMap. */
230         public boolean containsValue(Object k) { return containsKey(k); }
231
232
233         // UGLY
234         public Object[] dumpkeys() {
235             Object[] ret = new Object[size];
236             int pos = 0;
237             for(int i=0; i<entries.length; i+=indexmultiple)
238                 if (placeholder!=entries[i] && entries[i]!=null) {
239                     ret[pos++] = entries[i];
240                 }
241             return ret;
242         }
243
244         public void remove(Object k) { remove(indexOf(k)); }
245         public void remove(int dest) {
246             if (dest < 0) return;
247             // instead of removing, insert a placeholder
248             entries[dest] = placeholder;
249             for (int inc=1; inc < indexmultiple; inc++) entries[dest + inc] = null;
250             size--;
251             placeholders++;
252         }
253
254         public Object get(Object key) { return get(key, 0); }
255         public Object get(Object key, int whichval) {
256             int i = indexOf(key);
257             return i >= 0 ? entries[i + 1 + whichval] : null;
258         }
259
260         public Object put(Object key, Object value) { return put(key, value, 0); }
261         public Object put(Object key, Object value, int whichval) {
262             if (loadFactor * (size + placeholders) > entries.length) rehash();
263             int dest = indexOf(key);
264             Object old = null;
265             if (dest < 0) {
266                 dest = -1 * (dest + 1);
267                 if (entries[dest] != placeholder) size++;
268                 entries[dest] = key;
269                 for(int i=1; i<indexmultiple; i++) entries[dest+i] = null;
270             } else {
271                 old = entries[dest + 1 + whichval];
272             }
273             entries[dest + 1 + whichval] = value;
274             return old;
275         }
276
277         /*
278         public boolean containsKey(Object k) { return super.containsValue(k); }
279         public boolean containsValue(Object v) {
280             for (int i=0; i < entries.length/indexmultiple; i++)
281                 if ((i == 0 || entries[i * indexmultiple] != null) && // exception for null key
282                     !equals(placeholder, entries[i * indexmultiple]) &&
283                     v == null ? entries[i + 1] == null : v.equals(entries[i + 1]))
284                         return true;
285             return false;
286         }
287         */
288
289         /** Compares two keys for equality. <tt>userKey</tt> is the key
290          *  passed to the map, <tt>storedKey</tt> is from the map.
291          *
292          * <p>Default implementation provides standard Java equality
293          * testing, <tt>k1 == null ? k2 == null : k1.equals(k2)</tt>.</p>
294          */
295         protected boolean equals(Object userKey, Object storedKey) {
296             return userKey == null ? storedKey == null : userKey.equals(storedKey);
297         }
298
299         /** Returns the array position in <tt>entries</tt>, adjusted for
300          *  <tt>indexmultiple</tt>, where <tt>k</tt> is/should be stored
301          *  using Radke's quadratic residue linear probing. 
302          *
303          *  <p><tt>entries[0]</tt> is a hard coded exception for the null
304          *  key.</p>
305          *  
306          * <p>If the key is not found, this function returns
307          * <tt>(-1 * indexPosition) - 1</tt>, where <tt>indexPosition</tt>
308          * is the array position where the mapping should be stored.</p>
309          *
310          * <p>Uses <tt>placeholder</tt> as a placeholder object, and
311          * compares keys using <tt>equals(Object, Object)</tt>.</p>
312          */
313         private int indexOf(Object k) {
314             // special case null key
315             if (k == null) return equals(placeholder, entries[0]) ? -1 : 0;
316
317             int hash = k == null ? 0 : k.hashCode();
318             final int orig = Math.abs(hash) % (entries.length / indexmultiple);
319             int dest = orig * indexmultiple;
320             int tries = 1;
321             boolean plus = true;
322
323             while (entries[dest] != null) {
324                 if (equals(k, entries[dest])) return dest;
325                 dest = Math.abs((orig + (plus ? 1 : -1) * tries * tries) % (entries.length / indexmultiple)) * indexmultiple;
326                 if (plus) tries++;
327                 plus = !plus;
328             }
329             return -1 * dest - 1;
330         }
331
332         /** Doubles the available entry space, first by packing the data
333          *  set (removes <tt>placeholder</tt> references) and if necessary
334          *  by increasing the size of the <tt>entries</tt> array.
335          */
336         private void rehash() {
337             Object[] oldentries = entries;
338             entries = new Object[oldentries.length * indexmultiple];
339
340             for (int i=0; i < (oldentries.length/indexmultiple); i++) {
341                 int pos = i * indexmultiple;
342                 if (pos > 0 && oldentries[pos] == null) continue;
343                 if (oldentries[pos] == placeholder) continue;
344
345                 // dont adjust any of the support entries
346                 int dest = indexOf(oldentries[pos]);
347                 dest = -1 * dest - 1; size++;  // always new entry
348                 for (int inc=0; inc < indexmultiple; inc++)
349                     entries[dest + inc] = oldentries[pos + inc];
350             }
351             placeholders = 0;
352         }
353     }
354
355     // FIXME, BalancedTree goes here
356
357 }