Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

BlockList.java 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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.util;
  44. import java.util.AbstractList;
  45. import java.util.Arrays;
  46. import java.util.Iterator;
  47. import java.util.NoSuchElementException;
  48. /**
  49. * Random access list that allocates entries in blocks.
  50. * <p>
  51. * Unlike {@link java.util.ArrayList}, this type does not need to reallocate the
  52. * internal array in order to expand the capacity of the list. Access to any
  53. * element is constant time, but requires two array lookups instead of one.
  54. * <p>
  55. * To handle common usages, {@link #add(Object)} and {@link #iterator()} use
  56. * internal code paths to amortize out the second array lookup, making addition
  57. * and simple iteration closer to one array operation per element processed.
  58. * <p>
  59. * Similar to {@code ArrayList}, adding or removing from any position except the
  60. * end of the list requires O(N) time to copy all elements between the
  61. * modification point and the end of the list. Applications are strongly
  62. * encouraged to not use this access pattern with this list implementation.
  63. *
  64. * @param <T>
  65. * type of list element.
  66. */
  67. public class BlockList<T> extends AbstractList<T> {
  68. private static final int BLOCK_BITS = 10;
  69. static final int BLOCK_SIZE = 1 << BLOCK_BITS;
  70. private static final int BLOCK_MASK = BLOCK_SIZE - 1;
  71. private T[][] directory;
  72. private int size;
  73. private int tailDirIdx;
  74. private int tailBlkIdx;
  75. private T[] tailBlock;
  76. /** Initialize an empty list. */
  77. public BlockList() {
  78. directory = BlockList.<T> newDirectory(256);
  79. directory[0] = BlockList.<T> newBlock();
  80. tailBlock = directory[0];
  81. }
  82. /**
  83. * Initialize an empty list with an expected capacity.
  84. *
  85. * @param capacity
  86. * number of elements expected to be in the list.
  87. */
  88. public BlockList(int capacity) {
  89. int dirSize = toDirectoryIndex(capacity);
  90. if ((capacity & BLOCK_MASK) != 0 || dirSize == 0)
  91. dirSize++;
  92. directory = BlockList.<T> newDirectory(dirSize);
  93. directory[0] = BlockList.<T> newBlock();
  94. tailBlock = directory[0];
  95. }
  96. @Override
  97. public int size() {
  98. return size;
  99. }
  100. @Override
  101. public void clear() {
  102. for (T[] block : directory) {
  103. if (block != null)
  104. Arrays.fill(block, null);
  105. }
  106. size = 0;
  107. tailDirIdx = 0;
  108. tailBlkIdx = 0;
  109. tailBlock = directory[0];
  110. }
  111. @Override
  112. public T get(int index) {
  113. if (index < 0 || size <= index)
  114. throw new IndexOutOfBoundsException(String.valueOf(index));
  115. return directory[toDirectoryIndex(index)][toBlockIndex(index)];
  116. }
  117. @Override
  118. public T set(int index, T element) {
  119. if (index < 0 || size <= index)
  120. throw new IndexOutOfBoundsException(String.valueOf(index));
  121. T[] blockRef = directory[toDirectoryIndex(index)];
  122. int blockIdx = toBlockIndex(index);
  123. T old = blockRef[blockIdx];
  124. blockRef[blockIdx] = element;
  125. return old;
  126. }
  127. /**
  128. * Quickly append all elements of another BlockList.
  129. *
  130. * @param src
  131. * the list to copy elements from.
  132. */
  133. public void addAll(BlockList<T> src) {
  134. if (src.size == 0)
  135. return;
  136. int srcDirIdx = 0;
  137. for (; srcDirIdx < src.tailDirIdx; srcDirIdx++)
  138. addAll(src.directory[srcDirIdx], 0, BLOCK_SIZE);
  139. if (src.tailBlkIdx != 0)
  140. addAll(src.tailBlock, 0, src.tailBlkIdx);
  141. }
  142. /**
  143. * Quickly append all elements from an array.
  144. *
  145. * @param src
  146. * the source array.
  147. * @param srcIdx
  148. * first index to copy.
  149. * @param srcCnt
  150. * number of elements to copy.
  151. */
  152. public void addAll(T[] src, int srcIdx, int srcCnt) {
  153. while (0 < srcCnt) {
  154. int i = tailBlkIdx;
  155. int n = Math.min(srcCnt, BLOCK_SIZE - i);
  156. if (n == 0) {
  157. // Our tail is full, expand by one.
  158. add(src[srcIdx++]);
  159. srcCnt--;
  160. continue;
  161. }
  162. System.arraycopy(src, srcIdx, tailBlock, i, n);
  163. tailBlkIdx += n;
  164. size += n;
  165. srcIdx += n;
  166. srcCnt -= n;
  167. }
  168. }
  169. @Override
  170. public boolean add(T element) {
  171. int i = tailBlkIdx;
  172. if (i < BLOCK_SIZE) {
  173. // Fast-path: Append to current tail block.
  174. tailBlock[i] = element;
  175. tailBlkIdx = i + 1;
  176. size++;
  177. return true;
  178. }
  179. // Slow path: Move to the next block, expanding if necessary.
  180. if (++tailDirIdx == directory.length) {
  181. T[][] newDir = BlockList.<T> newDirectory(directory.length << 1);
  182. System.arraycopy(directory, 0, newDir, 0, directory.length);
  183. directory = newDir;
  184. }
  185. T[] blockRef = directory[tailDirIdx];
  186. if (blockRef == null) {
  187. blockRef = BlockList.<T> newBlock();
  188. directory[tailDirIdx] = blockRef;
  189. }
  190. blockRef[0] = element;
  191. tailBlock = blockRef;
  192. tailBlkIdx = 1;
  193. size++;
  194. return true;
  195. }
  196. @Override
  197. public void add(int index, T element) {
  198. if (index == size) {
  199. // Fast-path: append onto the end of the list.
  200. add(element);
  201. } else if (index < 0 || size < index) {
  202. throw new IndexOutOfBoundsException(String.valueOf(index));
  203. } else {
  204. // Slow-path: the list needs to expand and insert.
  205. // Do this the naive way, callers shouldn't abuse
  206. // this class by entering this code path.
  207. //
  208. add(null); // expand the list by one
  209. for (int oldIdx = size - 2; index <= oldIdx; oldIdx--)
  210. set(oldIdx + 1, get(oldIdx));
  211. set(index, element);
  212. }
  213. }
  214. @Override
  215. public T remove(int index) {
  216. if (index == size - 1) {
  217. // Fast-path: remove the last element.
  218. T[] blockRef = directory[toDirectoryIndex(index)];
  219. int blockIdx = toBlockIndex(index);
  220. T old = blockRef[blockIdx];
  221. blockRef[blockIdx] = null;
  222. size--;
  223. if (0 < tailBlkIdx)
  224. tailBlkIdx--;
  225. else
  226. resetTailBlock();
  227. return old;
  228. } else if (index < 0 || size <= index) {
  229. throw new IndexOutOfBoundsException(String.valueOf(index));
  230. } else {
  231. // Slow-path: the list needs to contract and remove.
  232. // Do this the naive way, callers shouldn't abuse
  233. // this class by entering this code path.
  234. //
  235. T old = get(index);
  236. for (; index < size - 1; index++)
  237. set(index, get(index + 1));
  238. set(size - 1, null);
  239. size--;
  240. resetTailBlock();
  241. return old;
  242. }
  243. }
  244. private void resetTailBlock() {
  245. tailDirIdx = toDirectoryIndex(size);
  246. tailBlkIdx = toBlockIndex(size);
  247. tailBlock = directory[tailDirIdx];
  248. }
  249. @Override
  250. public Iterator<T> iterator() {
  251. return new MyIterator();
  252. }
  253. private static final int toDirectoryIndex(int index) {
  254. return index >>> BLOCK_BITS;
  255. }
  256. private static final int toBlockIndex(int index) {
  257. return index & BLOCK_MASK;
  258. }
  259. @SuppressWarnings("unchecked")
  260. private static <T> T[][] newDirectory(int size) {
  261. return (T[][]) new Object[size][];
  262. }
  263. @SuppressWarnings("unchecked")
  264. private static <T> T[] newBlock() {
  265. return (T[]) new Object[BLOCK_SIZE];
  266. }
  267. private class MyIterator implements Iterator<T> {
  268. private int index;
  269. private int dirIdx;
  270. private int blkIdx;
  271. private T[] block = directory[0];
  272. public boolean hasNext() {
  273. return index < size;
  274. }
  275. public T next() {
  276. if (size <= index)
  277. throw new NoSuchElementException();
  278. T res = block[blkIdx];
  279. if (++blkIdx == BLOCK_SIZE) {
  280. if (++dirIdx < directory.length)
  281. block = directory[dirIdx];
  282. else
  283. block = null;
  284. blkIdx = 0;
  285. }
  286. index++;
  287. return res;
  288. }
  289. public void remove() {
  290. if (index == 0)
  291. throw new IllegalStateException();
  292. BlockList.this.remove(--index);
  293. dirIdx = toDirectoryIndex(index);
  294. blkIdx = toBlockIndex(index);
  295. block = directory[dirIdx];
  296. }
  297. }
  298. }