]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/BinaryQueryHash.java
Generate parts of db client query code
[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.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: BinaryQueryHash.java,v 1.2 2008/03/14 11:38:53 tuoksk Exp $
29  */
30 abstract public class BinaryQueryHash<Procedure> extends THash {
31     static final long serialVersionUID = -3461112548087185871L;
32
33     /** the set of Objects */
34     protected transient BinaryQuery<Procedure>[] _set;
35
36     protected final BinaryQuery<Procedure> REMOVED = new BinaryQuery<Procedure>(-1, -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 Object compute(ReadGraphImpl graph, Procedure procedure) throws DatabaseException {
50             throw new Error("Not possible!");
51                 }
52
53                 @Override
54                 Object performFromCache(ReadGraphImpl graph, Procedure procedure) throws DatabaseException {
55             throw new Error("Not possible!");
56                 }
57
58                 @Override
59                 public void recompute(ReadGraphImpl graph) 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 BinaryQueryHash() {
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 = (BinaryQuery[])Array.newInstance(BinaryQuery.class, capacity);
94         return capacity;
95         
96     }
97
98     final protected int index(final long id) {
99
100         final BinaryQuery<Procedure>[] set = _set;
101         final int length = set.length;
102         final int hash = ((31 * ((int)(id>>>32)) + (int)id) )& 0x7fffffff;
103         int index = hash % length;
104         BinaryQuery<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
128     /**
129      * Locates the index at which <tt>obj</tt> can be inserted.  if
130      * there is already a value equal()ing <tt>obj</tt> in the set,
131      * returns that value's index as <tt>-index - 1</tt>.
132      *
133      * @param obj an <code>Object</code> value
134      * @return the index of a FREE slot at which obj can be inserted
135      * or, if obj is already stored in the hash, the negative value of
136      * that index, minus 1: -index -1.
137      */
138     final protected int insertionIndex(final long id) {
139
140         final BinaryQuery<Procedure>[] set = _set;
141         final int length = set.length;
142         final int hash = (31 * ((int)(id>>>32)) + (int)id) & 0x7fffffff;
143         int index = hash % length;
144         BinaryQuery<Procedure> cur = set[index];
145
146         if (cur == null) {
147             return index;       // empty, all done
148         } else if (cur != REMOVED && (id == cur.id)) {
149             return -index -1;   // already stored
150         } else {                // already FULL or REMOVED, must probe
151             // compute the double hash
152             final int probe = 1 + (hash % (length - 2));
153
154             // if the slot we landed on is FULL (but not removed), probe
155             // until we find an empty slot, a REMOVED slot, or an element
156             // equal to the one we are trying to insert.
157             // finding an empty slot means that the value is not present
158             // and that we should use that slot as the insertion point;
159             // finding a REMOVED slot means that we need to keep searching,
160             // however we want to remember the offset of that REMOVED slot
161             // so we can reuse it in case a "new" insertion (i.e. not an update)
162             // is possible.
163             // finding a matching value means that we've found that our desired
164             // key is already in the table
165             if (cur != REMOVED) {
166                 // starting at the natural offset, probe until we find an
167                 // offset that isn't full.
168                 do {
169                     index -= probe;
170                     if (index < 0) {
171                         index += length;
172                     }
173                     cur = set[index];
174                 } while (cur != null
175                          && cur != REMOVED
176                          && ! (id == cur.id));
177             }
178
179             // if the index we found was removed: continue probing until we
180             // locate a free location or an element which equal()s the
181             // one we have.
182             if (cur == REMOVED) {
183                 int firstRemoved = index;
184                 while (cur != null
185                        && (cur == REMOVED || ! (id == cur.id))) {
186                     index -= probe;
187                     if (index < 0) {
188                         index += length;
189                     }
190                     cur = set[index];
191                 }
192                 // NOTE: cur cannot == REMOVED in this block
193                 return (cur != null) ? -index -1 : firstRemoved;
194             }
195             // if it's full, the key is already stored
196             // NOTE: cur cannot equal REMOVE here (would have retuned already (see above)
197             return (cur != null) ? -index -1 : index;
198         }
199     }
200
201     /**
202      * Convenience methods for subclasses to use in throwing exceptions about
203      * badly behaved user objects employed as keys.  We have to throw an
204      * IllegalArgumentException with a rather verbose message telling the
205      * user that they need to fix their object implementation to conform
206      * to the general contract for java.lang.Object.
207      *
208      * @param o1 the first of the equal elements with unequal hash codes.
209      * @param o2 the second of the equal elements with unequal hash codes.
210      * @exception IllegalArgumentException the whole point of this method.
211      */
212     protected final void throwObjectContractViolation(Object o1, Object o2)
213         throws IllegalArgumentException {
214         throw new IllegalArgumentException("Equal objects must have equal hashcodes. "
215                                            + "During rehashing, Trove discovered that "
216                                            + "the following two objects claim to be "
217                                            + "equal (as in java.lang.Object.equals()) "
218                                            + "but their hashCodes (or those calculated by "
219                                            + "your TObjectHashingStrategy) are not equal."
220                                            + "This violates the general contract of "
221                                            + "java.lang.Object.hashCode().  See bullet point two "
222                                            + "in that method's documentation. "
223                                            + "object #1 =" + o1 + " object #1 hash = " + o1.hashCode() + " object #1 id = " + System.identityHashCode(o1)
224                                            + "; object #2 =" + o2 + " object #2 hash = " + o2.hashCode() + " object #2 id = " + System.identityHashCode(o2));
225     }
226 } // TObjectHash