]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/UnaryQueryHash.java
Generate parts of db client query code
[simantics/platform.git] / bundles / org.simantics.db.impl / src / org / simantics / db / impl / query / UnaryQueryHash.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.exception.DatabaseException;
19 import org.simantics.db.impl.graph.ReadGraphImpl;
20
21
22 /**
23  * An open addressed hashing implementation for Object types.
24  *
25  * Created: Sun Nov  4 08:56:06 2001
26  *
27  * @author Eric D. Friedman
28  * @version $Id: UnaryQueryHash.java,v 1.2 2008/03/14 11:38:53 tuoksk Exp $
29  */
30 abstract public class UnaryQueryHash<Procedure> extends THash {
31     static final long serialVersionUID = -3461112548087185871L;
32
33     /** the set of Objects */
34     protected transient UnaryQuery<Procedure>[] _set;
35
36     protected final UnaryQuery<Procedure> REMOVED = new UnaryQuery<Procedure>(-1) {
37
38         @Override
39         public void removeEntry(QueryProcessor provider) {
40             throw new Error("Not possible.");
41         }
42
43         @Override
44         public int type() {
45             throw new Error("Not possible.");
46         }
47
48                 @Override
49                 public void recompute(ReadGraphImpl graph) throws DatabaseException {
50             throw new Error("Not possible.");
51                 }
52
53                 @Override
54                 public Object compute(ReadGraphImpl graph, Procedure procedure) throws DatabaseException {
55             throw new Error("Not possible.");
56                 }
57
58                 @Override
59                 Object performFromCache(ReadGraphImpl graph, Procedure procedure) throws DatabaseException {
60             throw new Error("Not possible.");
61                 }
62         
63     };
64
65     /**
66      * Creates a new <code>TObjectHash</code> instance with the
67      * default capacity and load factor.
68      */
69     public UnaryQueryHash() {
70         super(DEFAULT_CAPACITY, 0.75f);
71     }
72
73     public int capacity() {
74         return _set.length;
75     }
76
77     protected void removeAt(int index) {
78         _set[index] = REMOVED;
79         super.removeAt(index);
80     }
81
82     /**
83      * initializes the Object set of this hash table.
84      *
85      * @param initialCapacity an <code>int</code> value
86      * @return an <code>int</code> value
87      */
88     @SuppressWarnings("unchecked")
89         protected int setUp(int initialCapacity) {
90         int capacity;
91
92         capacity = super.setUp(initialCapacity);
93         _set = (UnaryQuery[])Array.newInstance(UnaryQuery.class, capacity);
94         return capacity;
95         
96     }
97
98     protected int index(final int id) {
99
100         final UnaryQuery<Procedure>[] set = _set;
101         final int length = set.length;
102         final int hash = (31 * id) & 0x7fffffff;
103         int index = hash % length;
104         UnaryQuery<Procedure> cur = set[index];
105
106         if ( cur == null ) return -1;
107
108         // NOTE: here it has to be REMOVED or FULL (some user-given value)
109         if ( cur == REMOVED || !(id == cur.id)) {
110             // see Knuth, p. 529
111             final int probe = 1 + (hash % (length - 2));
112
113             do {
114                 index -= probe;
115                 if (index < 0) {
116                     index += length;
117                 }
118                 cur = set[index];
119             } while (cur != null
120                  && (cur == REMOVED || !(id == cur.id)));
121         }
122
123         return cur == null ? -1 : index;
124         
125     }
126     
127     final protected UnaryQuery<Procedure> index2(final int id) {
128
129         final UnaryQuery<Procedure>[] set = _set;
130         final int length = set.length;
131         final int hash = (31 * id) & 0x7fffffff;
132         int index = hash % length;
133         UnaryQuery<Procedure> cur = set[index];
134
135         if ( cur == null ) return null;
136
137         // NOTE: here it has to be REMOVED or FULL (some user-given value)
138         if ( cur == REMOVED || (id != cur.id)) {
139             // see Knuth, p. 529
140             final int probe = 1 + (hash % (length - 2));
141
142             do {
143                 index -= probe;
144                 if (index < 0) {
145                     index += length;
146                 }
147                 cur = set[index];
148             } while (cur != null
149                  && (cur == REMOVED || (id != cur.id)));
150         }
151
152         return cur;
153         
154     }
155
156     
157     /**
158      * Locates the index at which <tt>obj</tt> can be inserted.  if
159      * there is already a value equal()ing <tt>obj</tt> in the set,
160      * returns that value's index as <tt>-index - 1</tt>.
161      *
162      * @param obj an <code>Object</code> value
163      * @return the index of a FREE slot at which obj can be inserted
164      * or, if obj is already stored in the hash, the negative value of
165      * that index, minus 1: -index -1.
166      */
167     protected int insertionIndex(final int id) {
168
169         final UnaryQuery<Procedure>[] set = _set;
170         final int length = set.length;
171         final int hash = (31 * id) & 0x7fffffff;
172         int index = hash % length;
173         UnaryQuery<Procedure> cur = set[index];
174
175         if (cur == null) {
176             return index;       // empty, all done
177         } else if (cur != REMOVED && (id == cur.id)) {
178             return -index -1;   // already stored
179         } else {                // already FULL or REMOVED, must probe
180             // compute the double hash
181             final int probe = 1 + (hash % (length - 2));
182
183             // if the slot we landed on is FULL (but not removed), probe
184             // until we find an empty slot, a REMOVED slot, or an element
185             // equal to the one we are trying to insert.
186             // finding an empty slot means that the value is not present
187             // and that we should use that slot as the insertion point;
188             // finding a REMOVED slot means that we need to keep searching,
189             // however we want to remember the offset of that REMOVED slot
190             // so we can reuse it in case a "new" insertion (i.e. not an update)
191             // is possible.
192             // finding a matching value means that we've found that our desired
193             // key is already in the table
194             if (cur != REMOVED) {
195                 // starting at the natural offset, probe until we find an
196                 // offset that isn't full.
197                 do {
198                     index -= probe;
199                     if (index < 0) {
200                         index += length;
201                     }
202                     cur = set[index];
203                 } while (cur != null
204                          && cur != REMOVED
205                          && ! (id == cur.id));
206             }
207
208             // if the index we found was removed: continue probing until we
209             // locate a free location or an element which equal()s the
210             // one we have.
211             if (cur == REMOVED) {
212                 int firstRemoved = index;
213                 while (cur != null
214                        && (cur == REMOVED || ! (id == cur.id))) {
215                     index -= probe;
216                     if (index < 0) {
217                         index += length;
218                     }
219                     cur = set[index];
220                 }
221                 // NOTE: cur cannot == REMOVED in this block
222                 return (cur != null) ? -index -1 : firstRemoved;
223             }
224             // if it's full, the key is already stored
225             // NOTE: cur cannot equal REMOVE here (would have retuned already (see above)
226             return (cur != null) ? -index -1 : index;
227         }
228     }
229
230     protected int insertionIndex2(final int id, final UnaryQuery<Procedure>[] set) {
231
232         final int length = set.length;
233         final int hash = (31 * id) & 0x7fffffff;
234         int index = hash % length;
235         UnaryQuery<Procedure> cur = set[index];
236
237         if (cur == null) {
238             return index;       // empty, all done
239         } else if (cur != REMOVED && (id == cur.id)) {
240             return -index -1;   // already stored
241         } else {                // already FULL or REMOVED, must probe
242             // compute the double hash
243             final int probe = 1 + (hash % (length - 2));
244
245             // if the slot we landed on is FULL (but not removed), probe
246             // until we find an empty slot, a REMOVED slot, or an element
247             // equal to the one we are trying to insert.
248             // finding an empty slot means that the value is not present
249             // and that we should use that slot as the insertion point;
250             // finding a REMOVED slot means that we need to keep searching,
251             // however we want to remember the offset of that REMOVED slot
252             // so we can reuse it in case a "new" insertion (i.e. not an update)
253             // is possible.
254             // finding a matching value means that we've found that our desired
255             // key is already in the table
256             if (cur != REMOVED) {
257                 // starting at the natural offset, probe until we find an
258                 // offset that isn't full.
259                 do {
260                     index -= probe;
261                     if (index < 0) {
262                         index += length;
263                     }
264                     cur = set[index];
265                 } while (cur != null
266                          && cur != REMOVED
267                          && ! (id == cur.id));
268             }
269
270             // if the index we found was removed: continue probing until we
271             // locate a free location or an element which equal()s the
272             // one we have.
273             if (cur == REMOVED) {
274                 int firstRemoved = index;
275                 while (cur != null
276                        && (cur == REMOVED || ! (id == cur.id))) {
277                     index -= probe;
278                     if (index < 0) {
279                         index += length;
280                     }
281                     cur = set[index];
282                 }
283                 // NOTE: cur cannot == REMOVED in this block
284                 return (cur != null) ? -index -1 : firstRemoved;
285             }
286             // if it's full, the key is already stored
287             // NOTE: cur cannot equal REMOVE here (would have retuned already (see above)
288             return (cur != null) ? -index -1 : index;
289         }
290     }
291
292     /**
293      * Convenience methods for subclasses to use in throwing exceptions about
294      * badly behaved user objects employed as keys.  We have to throw an
295      * IllegalArgumentException with a rather verbose message telling the
296      * user that they need to fix their object implementation to conform
297      * to the general contract for java.lang.Object.
298      *
299      * @param o1 the first of the equal elements with unequal hash codes.
300      * @param o2 the second of the equal elements with unequal hash codes.
301      * @exception IllegalArgumentException the whole point of this method.
302      */
303     protected final void throwObjectContractViolation(Object o1, Object o2)
304         throws IllegalArgumentException {
305         throw new IllegalArgumentException("Equal objects must have equal hashcodes. "
306                                            + "During rehashing, Trove discovered that "
307                                            + "the following two objects claim to be "
308                                            + "equal (as in java.lang.Object.equals()) "
309                                            + "but their hashCodes (or those calculated by "
310                                            + "your TObjectHashingStrategy) are not equal."
311                                            + "This violates the general contract of "
312                                            + "java.lang.Object.hashCode().  See bullet point two "
313                                            + "in that method's documentation. "
314                                            + "object #1 =" + o1
315                                            + "; object #2 =" + o2);
316     }
317 } // TObjectHash