You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ObjectIdOwnerMap.java 9.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. /*
  2. * Copyright (C) 2011, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.lib;
  44. import java.util.Arrays;
  45. import java.util.Iterator;
  46. import java.util.NoSuchElementException;
  47. /**
  48. * Fast, efficient map for {@link ObjectId} subclasses in only one map.
  49. * <p>
  50. * To use this map type, applications must have their entry value type extend
  51. * from {@link ObjectIdOwnerMap.Entry}, which itself extends from ObjectId.
  52. * <p>
  53. * Object instances may only be stored in <b>ONE</b> ObjectIdOwnerMap. This
  54. * restriction exists because the map stores internal map state within each
  55. * object instance. If an instance is be placed in another ObjectIdOwnerMap it
  56. * could corrupt one or both map's internal state.
  57. * <p>
  58. * If an object instance must be in more than one map, applications may use
  59. * ObjectIdOwnerMap for one of the maps, and {@link ObjectIdSubclassMap} for the
  60. * other map(s). It is encouraged to use ObjectIdOwnerMap for the map that is
  61. * accessed most often, as this implementation runs faster than the more general
  62. * ObjectIdSubclassMap implementation.
  63. *
  64. * @param <V>
  65. * type of subclass of ObjectId that will be stored in the map.
  66. */
  67. public class ObjectIdOwnerMap<V extends ObjectIdOwnerMap.Entry>
  68. implements Iterable<V>, ObjectIdSet {
  69. /** Size of the initial directory, will grow as necessary. */
  70. private static final int INITIAL_DIRECTORY = 1024;
  71. /** Number of bits in a segment's index. Segments are 2^11 in size. */
  72. private static final int SEGMENT_BITS = 11;
  73. private static final int SEGMENT_SHIFT = 32 - SEGMENT_BITS;
  74. /**
  75. * Top level directory of the segments.
  76. * <p>
  77. * The low {@link #bits} of the SHA-1 are used to select the segment from
  78. * this directory. Each segment is constant sized at 2^SEGMENT_BITS.
  79. */
  80. V[][] directory;
  81. /** Total number of objects in this map. */
  82. int size;
  83. /** The map doubles in capacity when {@link #size} reaches this target. */
  84. private int grow;
  85. /** Number of low bits used to form the index into {@link #directory}. */
  86. int bits;
  87. /** Low bit mask to index into {@link #directory}, {@code 2^bits-1}. */
  88. private int mask;
  89. /** Create an empty map. */
  90. @SuppressWarnings("unchecked")
  91. public ObjectIdOwnerMap() {
  92. bits = 0;
  93. mask = 0;
  94. grow = computeGrowAt(bits);
  95. directory = (V[][]) new Entry[INITIAL_DIRECTORY][];
  96. directory[0] = newSegment();
  97. }
  98. /** Remove all entries from this map. */
  99. public void clear() {
  100. size = 0;
  101. for (V[] tbl : directory) {
  102. if (tbl == null)
  103. break;
  104. Arrays.fill(tbl, null);
  105. }
  106. }
  107. /**
  108. * Lookup an existing mapping.
  109. *
  110. * @param toFind
  111. * the object identifier to find.
  112. * @return the instance mapped to toFind, or null if no mapping exists.
  113. */
  114. @SuppressWarnings("unchecked")
  115. public V get(final AnyObjectId toFind) {
  116. int h = toFind.w1;
  117. V obj = directory[h & mask][h >>> SEGMENT_SHIFT];
  118. for (; obj != null; obj = (V) obj.next)
  119. if (equals(obj, toFind))
  120. return obj;
  121. return null;
  122. }
  123. /**
  124. * Returns true if this map contains the specified object.
  125. *
  126. * @param toFind
  127. * object to find.
  128. * @return true if the mapping exists for this object; false otherwise.
  129. */
  130. @Override
  131. public boolean contains(final AnyObjectId toFind) {
  132. return get(toFind) != null;
  133. }
  134. /**
  135. * Store an object for future lookup.
  136. * <p>
  137. * An existing mapping for <b>must not</b> be in this map. Callers must
  138. * first call {@link #get(AnyObjectId)} to verify there is no current
  139. * mapping prior to adding a new mapping, or use {@link #addIfAbsent(Entry)}.
  140. *
  141. * @param newValue
  142. * the object to store.
  143. * @param <Q>
  144. * type of instance to store.
  145. */
  146. public <Q extends V> void add(final Q newValue) {
  147. if (++size == grow)
  148. grow();
  149. int h = newValue.w1;
  150. V[] table = directory[h & mask];
  151. h >>>= SEGMENT_SHIFT;
  152. newValue.next = table[h];
  153. table[h] = newValue;
  154. }
  155. /**
  156. * Store an object for future lookup.
  157. * <p>
  158. * Stores {@code newValue}, but only if there is not already an object for
  159. * the same object name. Callers can tell if the value is new by checking
  160. * the return value with reference equality:
  161. *
  162. * <pre>
  163. * V obj = ...;
  164. * boolean wasNew = map.addIfAbsent(obj) == obj;
  165. * </pre>
  166. *
  167. * @param newValue
  168. * the object to store.
  169. * @return {@code newValue} if stored, or the prior value already stored and
  170. * that would have been returned had the caller used
  171. * {@code get(newValue)} first.
  172. * @param <Q>
  173. * type of instance to store.
  174. */
  175. @SuppressWarnings("unchecked")
  176. public <Q extends V> V addIfAbsent(final Q newValue) {
  177. int h = newValue.w1;
  178. V[] table = directory[h & mask];
  179. h >>>= SEGMENT_SHIFT;
  180. for (V obj = table[h]; obj != null; obj = (V) obj.next)
  181. if (equals(obj, newValue))
  182. return obj;
  183. newValue.next = table[h];
  184. table[h] = newValue;
  185. if (++size == grow)
  186. grow();
  187. return newValue;
  188. }
  189. /** @return number of objects in this map. */
  190. public int size() {
  191. return size;
  192. }
  193. /** @return true if {@link #size()} is 0. */
  194. public boolean isEmpty() {
  195. return size == 0;
  196. }
  197. @Override
  198. public Iterator<V> iterator() {
  199. return new Iterator<V>() {
  200. private int found;
  201. private int dirIdx;
  202. private int tblIdx;
  203. private V next;
  204. @Override
  205. public boolean hasNext() {
  206. return found < size;
  207. }
  208. @Override
  209. public V next() {
  210. if (next != null)
  211. return found(next);
  212. for (;;) {
  213. V[] table = directory[dirIdx];
  214. if (tblIdx == table.length) {
  215. if (++dirIdx >= (1 << bits))
  216. throw new NoSuchElementException();
  217. table = directory[dirIdx];
  218. tblIdx = 0;
  219. }
  220. while (tblIdx < table.length) {
  221. V v = table[tblIdx++];
  222. if (v != null)
  223. return found(v);
  224. }
  225. }
  226. }
  227. @SuppressWarnings("unchecked")
  228. private V found(V v) {
  229. found++;
  230. next = (V) v.next;
  231. return v;
  232. }
  233. @Override
  234. public void remove() {
  235. throw new UnsupportedOperationException();
  236. }
  237. };
  238. }
  239. @SuppressWarnings("unchecked")
  240. private void grow() {
  241. final int oldDirLen = 1 << bits;
  242. final int s = 1 << bits;
  243. bits++;
  244. mask = (1 << bits) - 1;
  245. grow = computeGrowAt(bits);
  246. // Quadruple the directory if it needs to expand. Expanding the
  247. // directory is expensive because it generates garbage, so try
  248. // to avoid doing it often.
  249. //
  250. final int newDirLen = 1 << bits;
  251. if (directory.length < newDirLen) {
  252. V[][] newDir = (V[][]) new Entry[newDirLen << 1][];
  253. System.arraycopy(directory, 0, newDir, 0, oldDirLen);
  254. directory = newDir;
  255. }
  256. // For every bucket of every old segment, split the chain between
  257. // the old segment and the new segment's corresponding bucket. To
  258. // select between them use the lowest bit that was just added into
  259. // the mask above. This causes the table to double in capacity.
  260. //
  261. for (int dirIdx = 0; dirIdx < oldDirLen; dirIdx++) {
  262. final V[] oldTable = directory[dirIdx];
  263. final V[] newTable = newSegment();
  264. for (int i = 0; i < oldTable.length; i++) {
  265. V chain0 = null;
  266. V chain1 = null;
  267. V next;
  268. for (V obj = oldTable[i]; obj != null; obj = next) {
  269. next = (V) obj.next;
  270. if ((obj.w1 & s) == 0) {
  271. obj.next = chain0;
  272. chain0 = obj;
  273. } else {
  274. obj.next = chain1;
  275. chain1 = obj;
  276. }
  277. }
  278. oldTable[i] = chain0;
  279. newTable[i] = chain1;
  280. }
  281. directory[oldDirLen + dirIdx] = newTable;
  282. }
  283. }
  284. @SuppressWarnings("unchecked")
  285. private final V[] newSegment() {
  286. return (V[]) new Entry[1 << SEGMENT_BITS];
  287. }
  288. private static final int computeGrowAt(int bits) {
  289. return 1 << (bits + SEGMENT_BITS);
  290. }
  291. private static final boolean equals(AnyObjectId firstObjectId,
  292. AnyObjectId secondObjectId) {
  293. return firstObjectId.w2 == secondObjectId.w2
  294. && firstObjectId.w3 == secondObjectId.w3
  295. && firstObjectId.w4 == secondObjectId.w4
  296. && firstObjectId.w5 == secondObjectId.w5
  297. && firstObjectId.w1 == secondObjectId.w1;
  298. }
  299. /** Type of entry stored in the {@link ObjectIdOwnerMap}. */
  300. public static abstract class Entry extends ObjectId {
  301. transient Entry next;
  302. /**
  303. * Initialize this entry with a specific ObjectId.
  304. *
  305. * @param id
  306. * the id the entry represents.
  307. */
  308. public Entry(AnyObjectId id) {
  309. super(id);
  310. }
  311. }
  312. }