]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/BinaryQueryHash.java
3ac46276fe9d88f49f710eaa101ab8ef9210080b
[simantics/platform.git] / bundles / org.simantics.db.impl / src / org / simantics / db / impl / query / BinaryQueryHash.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.db.impl.query;
13
14 import gnu.trove.impl.hash.THash;
15
16 import java.lang.reflect.Array;
17
18 import org.simantics.db.impl.graph.ReadGraphImpl;
19
20
21 /**
22  * An open addressed hashing implementation for Object types.
23  *
24  * Created: Sun Nov  4 08:56:06 2001
25  *
26  * @author Eric D. Friedman
27  * @version $Id: BinaryQueryHash.java,v 1.2 2008/03/14 11:38:53 tuoksk Exp $
28  */
29 abstract public class BinaryQueryHash<Procedure> extends THash {
30     static final long serialVersionUID = -3461112548087185871L;
31
32     /** the set of Objects */
33     protected transient BinaryQuery<Procedure>[] _set;
34
35     protected final BinaryQuery<Procedure> REMOVED = new BinaryQuery<Procedure>(-1, -1) {
36
37         @Override
38         public void computeForEach(ReadGraphImpl graph, QueryProcessor provider, Object procedure, boolean store) {
39             throw new Error("Not possible!");
40         }
41
42         @Override
43         public void putEntry(QueryProcessor provider) {
44             throw new Error("Not possible!");
45         }
46
47         @Override
48         public BinaryQuery<Procedure> getEntry(QueryProcessor provider) {
49             throw new Error("Not possible!");
50         }
51
52         @Override
53         public void recompute(ReadGraphImpl graph, QueryProcessor provider) {
54             throw new Error("Not possible!");
55         }
56
57         @Override
58         public void removeEntry(QueryProcessor provider) {
59             throw new Error("Not possible!");
60         }
61
62 //        @Override
63 //        public ICacheEntry2 cachedEntry(Object provider) {
64 //            throw new Error("Not possible!");
65 //        }
66 //
67 //        @Override
68 //        public void computeForEach(int callerThread, Object provider, ICacheEntry2 parent, Object procedure) {
69 //            throw new Error("Not possible!");
70 //        }
71
72         @Override
73         public int type() {
74             throw new Error("Not possible!");
75         }
76
77                 @Override
78                 public Object performFromCache(ReadGraphImpl graph, QueryProcessor provider,
79                                 Procedure procedure) {
80             throw new Error("Not possible!");
81                 }
82
83                 @Override
84                 public Object performFromCache(ReadGraphImpl graph, Object provider,
85                                 Object procedure) {
86             throw new Error("Not possible!");
87                 }
88         
89     };
90
91     /**
92      * Creates a new <code>TObjectHash</code> instance with the
93      * default capacity and load factor.
94      */
95     public BinaryQueryHash() {
96         super(DEFAULT_CAPACITY, 0.75f);
97     }
98
99     public int capacity() {
100         return _set.length;
101     }
102
103     protected void removeAt(int index) {
104         _set[index] = REMOVED;
105         super.removeAt(index);
106     }
107
108     /**
109      * initializes the Object set of this hash table.
110      *
111      * @param initialCapacity an <code>int</code> value
112      * @return an <code>int</code> value
113      */
114     @SuppressWarnings("unchecked")
115         protected int setUp(int initialCapacity) {
116         int capacity;
117
118         capacity = super.setUp(initialCapacity);
119         _set = (BinaryQuery[])Array.newInstance(BinaryQuery.class, capacity);
120         return capacity;
121         
122     }
123
124     final protected int index(final long id) {
125
126         final BinaryQuery<Procedure>[] set = _set;
127         final int length = set.length;
128         final int hash = ((31 * ((int)(id>>>32)) + (int)id) )& 0x7fffffff;
129         int index = hash % length;
130         BinaryQuery<Procedure> cur = set[index];
131
132         if ( cur == null ) return -1;
133
134         // NOTE: here it has to be REMOVED or FULL (some user-given value)
135         if ( cur == REMOVED || !(id == cur.id)) {
136             // see Knuth, p. 529
137             final int probe = 1 + (hash % (length - 2));
138
139             do {
140                 index -= probe;
141                 if (index < 0) {
142                     index += length;
143                 }
144                 cur = set[index];
145             } while (cur != null
146                  && (cur == REMOVED || !(id == cur.id)));
147         }
148
149         return cur == null ? -1 : index;
150         
151     }
152     
153
154     /**
155      * Locates the index at which <tt>obj</tt> can be inserted.  if
156      * there is already a value equal()ing <tt>obj</tt> in the set,
157      * returns that value's index as <tt>-index - 1</tt>.
158      *
159      * @param obj an <code>Object</code> value
160      * @return the index of a FREE slot at which obj can be inserted
161      * or, if obj is already stored in the hash, the negative value of
162      * that index, minus 1: -index -1.
163      */
164     final protected int insertionIndex(final long id) {
165
166         final BinaryQuery<Procedure>[] set = _set;
167         final int length = set.length;
168         final int hash = (31 * ((int)(id>>>32)) + (int)id) & 0x7fffffff;
169         int index = hash % length;
170         BinaryQuery<Procedure> cur = set[index];
171
172         if (cur == null) {
173             return index;       // empty, all done
174         } else if (cur != REMOVED && (id == cur.id)) {
175             return -index -1;   // already stored
176         } else {                // already FULL or REMOVED, must probe
177             // compute the double hash
178             final int probe = 1 + (hash % (length - 2));
179
180             // if the slot we landed on is FULL (but not removed), probe
181             // until we find an empty slot, a REMOVED slot, or an element
182             // equal to the one we are trying to insert.
183             // finding an empty slot means that the value is not present
184             // and that we should use that slot as the insertion point;
185             // finding a REMOVED slot means that we need to keep searching,
186             // however we want to remember the offset of that REMOVED slot
187             // so we can reuse it in case a "new" insertion (i.e. not an update)
188             // is possible.
189             // finding a matching value means that we've found that our desired
190             // key is already in the table
191             if (cur != REMOVED) {
192                 // starting at the natural offset, probe until we find an
193                 // offset that isn't full.
194                 do {
195                     index -= probe;
196                     if (index < 0) {
197                         index += length;
198                     }
199                     cur = set[index];
200                 } while (cur != null
201                          && cur != REMOVED
202                          && ! (id == cur.id));
203             }
204
205             // if the index we found was removed: continue probing until we
206             // locate a free location or an element which equal()s the
207             // one we have.
208             if (cur == REMOVED) {
209                 int firstRemoved = index;
210                 while (cur != null
211                        && (cur == REMOVED || ! (id == cur.id))) {
212                     index -= probe;
213                     if (index < 0) {
214                         index += length;
215                     }
216                     cur = set[index];
217                 }
218                 // NOTE: cur cannot == REMOVED in this block
219                 return (cur != null) ? -index -1 : firstRemoved;
220             }
221             // if it's full, the key is already stored
222             // NOTE: cur cannot equal REMOVE here (would have retuned already (see above)
223             return (cur != null) ? -index -1 : index;
224         }
225     }
226
227     /**
228      * Convenience methods for subclasses to use in throwing exceptions about
229      * badly behaved user objects employed as keys.  We have to throw an
230      * IllegalArgumentException with a rather verbose message telling the
231      * user that they need to fix their object implementation to conform
232      * to the general contract for java.lang.Object.
233      *
234      * @param o1 the first of the equal elements with unequal hash codes.
235      * @param o2 the second of the equal elements with unequal hash codes.
236      * @exception IllegalArgumentException the whole point of this method.
237      */
238     protected final void throwObjectContractViolation(Object o1, Object o2)
239         throws IllegalArgumentException {
240         throw new IllegalArgumentException("Equal objects must have equal hashcodes. "
241                                            + "During rehashing, Trove discovered that "
242                                            + "the following two objects claim to be "
243                                            + "equal (as in java.lang.Object.equals()) "
244                                            + "but their hashCodes (or those calculated by "
245                                            + "your TObjectHashingStrategy) are not equal."
246                                            + "This violates the general contract of "
247                                            + "java.lang.Object.hashCode().  See bullet point two "
248                                            + "in that method's documentation. "
249                                            + "object #1 =" + o1 + " object #1 hash = " + o1.hashCode() + " object #1 id = " + System.identityHashCode(o1)
250                                            + "; object #2 =" + o2 + " object #2 hash = " + o2.hashCode() + " object #2 id = " + System.identityHashCode(o2));
251     }
252 } // TObjectHash