Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

ObjectIdOwnerMap.java 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. public boolean contains(final AnyObjectId toFind) {
  131. return get(toFind) != null;
  132. }
  133. /**
  134. * Store an object for future lookup.
  135. * <p>
  136. * An existing mapping for <b>must not</b> be in this map. Callers must
  137. * first call {@link #get(AnyObjectId)} to verify there is no current
  138. * mapping prior to adding a new mapping, or use {@link #addIfAbsent(Entry)}.
  139. *
  140. * @param newValue
  141. * the object to store.
  142. * @param <Q>
  143. * type of instance to store.
  144. */
  145. public <Q extends V> void add(final Q newValue) {
  146. if (++size == grow)
  147. grow();
  148. int h = newValue.w1;
  149. V[] table = directory[h & mask];
  150. h >>>= SEGMENT_SHIFT;
  151. newValue.next = table[h];
  152. table[h] = newValue;
  153. }
  154. /**
  155. * Store an object for future lookup.
  156. * <p>
  157. * Stores {@code newValue}, but only if there is not already an object for
  158. * the same object name. Callers can tell if the value is new by checking
  159. * the return value with reference equality:
  160. *
  161. * <pre>
  162. * V obj = ...;
  163. * boolean wasNew = map.addIfAbsent(obj) == obj;
  164. * </pre>
  165. *
  166. * @param newValue
  167. * the object to store.
  168. * @return {@code newValue} if stored, or the prior value already stored and
  169. * that would have been returned had the caller used
  170. * {@code get(newValue)} first.
  171. * @param <Q>
  172. * type of instance to store.
  173. */
  174. @SuppressWarnings("unchecked")
  175. public <Q extends V> V addIfAbsent(final Q newValue) {
  176. int h = newValue.w1;
  177. V[] table = directory[h & mask];
  178. h >>>= SEGMENT_SHIFT;
  179. for (V obj = table[h]; obj != null; obj = (V) obj.next)
  180. if (equals(obj, newValue))
  181. return obj;
  182. newValue.next = table[h];
  183. table[h] = newValue;
  184. if (++size == grow)
  185. grow();
  186. return newValue;
  187. }
  188. /** @return number of objects in this map. */
  189. public int size() {
  190. return size;
  191. }
  192. /** @return true if {@link #size()} is 0. */
  193. public boolean isEmpty() {
  194. return size == 0;
  195. }
  196. public Iterator<V> iterator() {
  197. return new Iterator<V>() {
  198. private int found;
  199. private int dirIdx;
  200. private int tblIdx;
  201. private V next;
  202. public boolean hasNext() {
  203. return found < size;
  204. }
  205. public V next() {
  206. if (next != null)
  207. return found(next);
  208. for (;;) {
  209. V[] table = directory[dirIdx];
  210. if (tblIdx == table.length) {
  211. if (++dirIdx >= (1 << bits))
  212. throw new NoSuchElementException();
  213. table = directory[dirIdx];
  214. tblIdx = 0;
  215. }
  216. while (tblIdx < table.length) {
  217. V v = table[tblIdx++];
  218. if (v != null)
  219. return found(v);
  220. }
  221. }
  222. }
  223. @SuppressWarnings("unchecked")
  224. private V found(V v) {
  225. found++;
  226. next = (V) v.next;
  227. return v;
  228. }
  229. public void remove() {
  230. throw new UnsupportedOperationException();
  231. }
  232. };
  233. }
  234. @SuppressWarnings("unchecked")
  235. private void grow() {
  236. final int oldDirLen = 1 << bits;
  237. final int s = 1 << bits;
  238. bits++;
  239. mask = (1 << bits) - 1;
  240. grow = computeGrowAt(bits);
  241. // Quadruple the directory if it needs to expand. Expanding the
  242. // directory is expensive because it generates garbage, so try
  243. // to avoid doing it often.
  244. //
  245. final int newDirLen = 1 << bits;
  246. if (directory.length < newDirLen) {
  247. V[][] newDir = (V[][]) new Entry[newDirLen << 1][];
  248. System.arraycopy(directory, 0, newDir, 0, oldDirLen);
  249. directory = newDir;
  250. }
  251. // For every bucket of every old segment, split the chain between
  252. // the old segment and the new segment's corresponding bucket. To
  253. // select between them use the lowest bit that was just added into
  254. // the mask above. This causes the table to double in capacity.
  255. //
  256. for (int dirIdx = 0; dirIdx < oldDirLen; dirIdx++) {
  257. final V[] oldTable = directory[dirIdx];
  258. final V[] newTable = newSegment();
  259. for (int i = 0; i < oldTable.length; i++) {
  260. V chain0 = null;
  261. V chain1 = null;
  262. V next;
  263. for (V obj = oldTable[i]; obj != null; obj = next) {
  264. next = (V) obj.next;
  265. if ((obj.w1 & s) == 0) {
  266. obj.next = chain0;
  267. chain0 = obj;
  268. } else {
  269. obj.next = chain1;
  270. chain1 = obj;
  271. }
  272. }
  273. oldTable[i] = chain0;
  274. newTable[i] = chain1;
  275. }
  276. directory[oldDirLen + dirIdx] = newTable;
  277. }
  278. }
  279. @SuppressWarnings("unchecked")
  280. private final V[] newSegment() {
  281. return (V[]) new Entry[1 << SEGMENT_BITS];
  282. }
  283. private static final int computeGrowAt(int bits) {
  284. return 1 << (bits + SEGMENT_BITS);
  285. }
  286. private static final boolean equals(AnyObjectId firstObjectId,
  287. AnyObjectId secondObjectId) {
  288. return firstObjectId.w2 == secondObjectId.w2
  289. && firstObjectId.w3 == secondObjectId.w3
  290. && firstObjectId.w4 == secondObjectId.w4
  291. && firstObjectId.w5 == secondObjectId.w5
  292. && firstObjectId.w1 == secondObjectId.w1;
  293. }
  294. /** Type of entry stored in the {@link ObjectIdOwnerMap}. */
  295. public static abstract class Entry extends ObjectId {
  296. Entry next;
  297. /**
  298. * Initialize this entry with a specific ObjectId.
  299. *
  300. * @param id
  301. * the id the entry represents.
  302. */
  303. public Entry(AnyObjectId id) {
  304. super(id);
  305. }
  306. }
  307. }