2 * Copyright (C) 2008 Shawn Pearce <spearce@spearce.org>
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License, version 2, as published by the Free Software Foundation.
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
17 package org
.spearce
.jgit
.lib
;
20 * Fast, efficient map specifically for {@link ObjectId} subclasses.
22 * This map provides an efficient translation from any ObjectId instance to a
23 * cached subclass of ObjectId that has the same value.
25 * Raw value equality is tested when comparing two ObjectIds (or subclasses),
26 * not reference equality and not <code>.equals(Object)</code> equality. This
27 * allows subclasses to override <code>equals</code> to supply their own
31 * type of subclass of ObjectId that will be stored in the map.
33 public class ObjectIdSubclassMap
<V
extends ObjectId
> {
38 /** Create an empty map. */
39 public ObjectIdSubclassMap() {
40 obj_hash
= createArray(32);
43 /** Remove all entries from this map. */
46 obj_hash
= createArray(32);
50 * Lookup an existing mapping.
53 * the object identifier to find.
54 * @return the instance mapped to toFind, or null if no mapping exists.
56 public V
get(final AnyObjectId toFind
) {
57 int i
= index(toFind
);
60 while ((obj
= obj_hash
[i
]) != null) {
61 if (AnyObjectId
.equals(obj
, toFind
))
63 if (++i
== obj_hash
.length
)
70 * Store an object for future lookup.
72 * An existing mapping for <b>must not</b> be in this map. Callers must
73 * first call {@link #get(AnyObjectId)} to verify there is no current
74 * mapping prior to adding a new mapping.
77 * the object to store.
80 * type of instance to store.
82 public <Q
extends V
> void add(final Q newValue
) {
83 if (obj_hash
.length
- 1 <= size
* 2)
89 private final int index(final AnyObjectId id
) {
90 return (id
.w1
>>> 1) % obj_hash
.length
;
93 private void insert(final V newValue
) {
94 int j
= index(newValue
);
95 while (obj_hash
[j
] != null) {
96 if (++j
>= obj_hash
.length
)
99 obj_hash
[j
] = newValue
;
102 private void grow() {
103 final V
[] old_hash
= obj_hash
;
104 final int old_hash_size
= obj_hash
.length
;
106 obj_hash
= createArray(2 * old_hash_size
);
107 for (int i
= 0; i
< old_hash_size
; i
++) {
108 final V obj
= old_hash
[i
];
114 @SuppressWarnings("unchecked")
115 private final V
[] createArray(final int sz
) {
116 return (V
[]) new ObjectId
[sz
];