Repository navigation
Expand file tree
/
Copy pathLongHashMap.java
More file actions
490 lines (415 loc) · 12.7 KB
/
Copy pathLongHashMap.java
File metadata and controls
490 lines (415 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mapdb;
import java.io.Serializable;
import java.util.*;
/**
* LongHashMap is an implementation of LongMap without concurrency locking.
* This code is adoption of 'HashMap' from Apache Harmony refactored to support primitive long keys.
*/
public class LongHashMap<V> extends LongMap<V> implements Serializable {
private static final long serialVersionUID = 362340234235222265L;
/*
* Actual count of entries
*/
transient int elementCount;
/*
* The internal data structure to hold Entries
*/
transient Entry<V>[] elementData;
/*
* modification count, to keep track of structural modifications between the
* HashMap and the iterator
*/
transient int modCount = 0;
/*
* default size that an HashMap created using the default constructor would
* have.
*/
private static final int DEFAULT_SIZE = 16;
/*
* maximum ratio of (stored elements)/(storage size) which does not lead to
* rehash
*/
final float loadFactor;
/**
* Salt added to keys before hashing, so it is harder to trigger hash collision attack.
*/
protected final long hashSalt = hashSaltValue();
protected long hashSaltValue() {
return new Random().nextLong();
}
/*
* maximum number of elements that can be put in this map before having to
* rehash
*/
int threshold;
static class Entry<V>{
final int origKeyHash;
final long key;
V value;
Entry<V> next;
public Entry(long key, int hash) {
this.key = key;
this.origKeyHash = hash;
}
}
private static class AbstractMapIterator<V> {
private int position = 0;
int expectedModCount;
Entry<V> futureEntry;
Entry<V> currentEntry;
Entry<V> prevEntry;
final LongHashMap<V> associatedMap;
AbstractMapIterator(LongHashMap<V> hm) {
associatedMap = hm;
expectedModCount = hm.modCount;
futureEntry = null;
}
public boolean hasNext() {
if (futureEntry != null) {
return true;
}
while (position < associatedMap.elementData.length) {
if (associatedMap.elementData[position] == null) {
position++;
} else {
return true;
}
}
return false;
}
final void checkConcurrentMod() throws ConcurrentModificationException {
if (expectedModCount != associatedMap.modCount) {
throw new ConcurrentModificationException();
}
}
final void makeNext() {
checkConcurrentMod();
if (!hasNext()) {
throw new NoSuchElementException();
}
if (futureEntry == null) {
currentEntry = associatedMap.elementData[position++];
futureEntry = currentEntry.next;
prevEntry = null;
} else {
if(currentEntry!=null){
prevEntry = currentEntry;
}
currentEntry = futureEntry;
futureEntry = futureEntry.next;
}
}
public final void remove() {
checkConcurrentMod();
if (currentEntry==null) {
throw new IllegalStateException();
}
if(prevEntry==null){
int index = currentEntry.origKeyHash & (associatedMap.elementData.length - 1);
associatedMap.elementData[index] = associatedMap.elementData[index].next;
} else {
prevEntry.next = currentEntry.next;
}
currentEntry = null;
expectedModCount++;
associatedMap.modCount++;
associatedMap.elementCount--;
}
}
private static class EntryIterator <V> extends AbstractMapIterator<V> implements LongMapIterator<V> {
EntryIterator (LongHashMap<V> map) {
super(map);
}
@Override
public boolean moveToNext() {
if(!hasNext()) return false;
makeNext();
return true;
}
@Override
public long key() {
return currentEntry.key;
}
@Override
public V value() {
return currentEntry.value;
}
}
private static class ValueIterator <V> extends AbstractMapIterator<V> implements Iterator<V> {
ValueIterator (LongHashMap<V> map) {
super(map);
}
@Override
public V next() {
makeNext();
return currentEntry.value;
}
}
/**
* Create a new element array
*
* @param s
* @return Reference to the element array
*/
@SuppressWarnings("unchecked")
Entry<V>[] newElementArray(int s) {
return new Entry[s];
}
/**
* Constructs a new empty {@code HashMap} instance.
*/
public LongHashMap() {
this(DEFAULT_SIZE);
}
/**
* Constructs a new {@code HashMap} instance with the specified capacity.
*
* @param capacity
* the initial capacity of this hash map.
* @throws IllegalArgumentException
* when the capacity is less than zero.
*/
public LongHashMap(int capacity) {
this(capacity, 0.75f); // default load factor of 0.75
}
/**
* Calculates the capacity of storage required for storing given number of
* elements
*
* @param x
* number of elements
* @return storage size
*/
private static int calculateCapacity(int x) {
if(x >= 1 << 30){
return 1 << 30;
}
if(x == 0){
return 16;
}
x = x -1;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x + 1;
}
/**
* Constructs a new {@code HashMap} instance with the specified capacity and
* load factor.
*
* @param capacity
* the initial capacity of this hash map.
* @param loadFactor
* the initial load factor.
* @throws IllegalArgumentException
* when the capacity is less than zero or the load factor is
* less or equal to zero.
*/
public LongHashMap(int capacity, float loadFactor) {
if (capacity >= 0 && loadFactor > 0) {
capacity = calculateCapacity(capacity);
elementCount = 0;
elementData = newElementArray(capacity);
this.loadFactor = loadFactor;
computeThreshold();
} else {
throw new IllegalArgumentException();
}
}
/**
* Removes all mappings from this hash map, leaving it empty.
*
* @see #isEmpty
* @see #size
*/
@Override
public void clear() {
if (elementCount > 0) {
elementCount = 0;
Arrays.fill(elementData, null);
modCount++;
}
}
/**
* Computes the threshold for rehashing
*/
private void computeThreshold() {
threshold = (int) (elementData.length * loadFactor);
}
/**
* Returns the value of the mapping with the specified key.
*
* @param key
* the key.
* @return the value of the mapping with the specified key, or {@code null}
* if no mapping for the specified key is found.
*/
@Override
public V get(long key) {
Entry<V> m = getEntry(key);
if (m != null) {
return m.value;
}
return null;
}
final Entry<V> getEntry(long key) {
int hash = LongHashMap.longHash(key^hashSalt);
int index = hash & (elementData.length - 1);
return findNonNullKeyEntry(key, index, hash);
}
final Entry<V> findNonNullKeyEntry(long key, int index, int keyHash) {
Entry<V> m = elementData[index];
while (m != null
&& (m.origKeyHash != keyHash || key!=m.key)) {
m = m.next;
}
return m;
}
/**
* Returns whether this map is empty.
*
* @return {@code true} if this map has no elements, {@code false}
* otherwise.
* @see #size()
*/
@Override
public boolean isEmpty() {
return elementCount == 0;
}
/**
* Maps the specified key to the specified value.
*
* @param key
* the key.
* @param value
* the value.
* @return the value of any previous mapping with the specified key or
* {@code null} if there was no such mapping.
*/
@Override
public V put(long key, V value) {
Entry<V> entry;
int hash = LongHashMap.longHash(key^hashSalt);
int index = hash & (elementData.length - 1);
entry = findNonNullKeyEntry(key, index, hash);
if (entry == null) {
modCount++;
entry = createHashedEntry(key, index, hash);
if (++elementCount > threshold) {
rehash();
}
}
V result = entry.value;
entry.value = value;
return result;
}
Entry<V> createHashedEntry(long key, int index, int hash) {
Entry<V> entry = new Entry<V>(key,hash);
entry.next = elementData[index];
elementData[index] = entry;
return entry;
}
void rehash(int capacity) {
int length = calculateCapacity((capacity == 0 ? 1 : capacity << 1));
Entry<V>[] newData = newElementArray(length);
for (int i = 0; i < elementData.length; i++) {
Entry<V> entry = elementData[i];
elementData[i] = null;
while (entry != null) {
int index = entry.origKeyHash & (length - 1);
Entry<V> next = entry.next;
entry.next = newData[index];
newData[index] = entry;
entry = next;
}
}
elementData = newData;
computeThreshold();
}
void rehash() {
rehash(elementData.length);
}
/**
* Removes the mapping with the specified key from this map.
*
* @param key
* the key of the mapping to remove.
* @return the value of the removed mapping or {@code null} if no mapping
* for the specified key was found.
*/
@Override
public V remove(long key) {
Entry<V> entry = removeEntry(key);
if (entry != null) {
return entry.value;
}
return null;
}
final Entry<V> removeEntry(long key) {
int index = 0;
Entry<V> entry;
Entry<V> last = null;
int hash = LongHashMap.longHash(key^hashSalt);
index = hash & (elementData.length - 1);
entry = elementData[index];
while (entry != null && !(entry.origKeyHash == hash && key == entry.key)) {
last = entry;
entry = entry.next;
}
if (entry == null) {
return null;
}
if (last == null) {
elementData[index] = entry.next;
} else {
last.next = entry.next;
}
modCount++;
elementCount--;
return entry;
}
/**
* Returns the number of elements in this map.
*
* @return the number of elements in this map.
*/
@Override
public int size() {
return elementCount;
}
@Override
public Iterator<V> valuesIterator() {
return new ValueIterator<V>(this);
}
@Override
public LongMapIterator<V> longMapIterator() {
return new EntryIterator<V>(this);
}
public static int longHash(final long key) {
int h = (int)(key ^ (key >>> 32));
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
public static int intHash(int h) {
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
}