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.

RefList.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. /*
  2. * Copyright (C) 2010, 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.Arrays;
  45. import java.util.Collections;
  46. import java.util.Iterator;
  47. import java.util.List;
  48. import java.util.NoSuchElementException;
  49. import java.util.function.BinaryOperator;
  50. import java.util.stream.Collector;
  51. import org.eclipse.jgit.annotations.Nullable;
  52. import org.eclipse.jgit.lib.Ref;
  53. import org.eclipse.jgit.lib.RefComparator;
  54. /**
  55. * Specialized variant of an ArrayList to support a {@code RefDatabase}.
  56. * <p>
  57. * This list is a hybrid of a Map&lt;String,Ref&gt; and of a List&lt;Ref&gt;. It
  58. * tracks reference instances by name by keeping them sorted and performing
  59. * binary search to locate an entry. Lookup time is O(log N), but addition and
  60. * removal is O(N + log N) due to the list expansion or contraction costs.
  61. * <p>
  62. * This list type is copy-on-write. Mutation methods return a new copy of the
  63. * list, leaving {@code this} unmodified. As a result we cannot easily implement
  64. * the {@link java.util.List} interface contract.
  65. *
  66. * @param <T>
  67. * the type of reference being stored in the collection.
  68. */
  69. public class RefList<T extends Ref> implements Iterable<Ref> {
  70. private static final RefList<Ref> EMPTY = new RefList<>(new Ref[0], 0);
  71. /**
  72. * Create an empty unmodifiable reference list.
  73. *
  74. * @return an empty unmodifiable reference list.
  75. */
  76. @SuppressWarnings("unchecked")
  77. public static <T extends Ref> RefList<T> emptyList() {
  78. return (RefList<T>) EMPTY;
  79. }
  80. final Ref[] list;
  81. final int cnt;
  82. RefList(Ref[] list, int cnt) {
  83. this.list = list;
  84. this.cnt = cnt;
  85. }
  86. /**
  87. * Initialize this list to use the same backing array as another list.
  88. *
  89. * @param src
  90. * the source list.
  91. */
  92. protected RefList(RefList<T> src) {
  93. this.list = src.list;
  94. this.cnt = src.cnt;
  95. }
  96. /** {@inheritDoc} */
  97. @Override
  98. public Iterator<Ref> iterator() {
  99. return new Iterator<Ref>() {
  100. private int idx;
  101. @Override
  102. public boolean hasNext() {
  103. return idx < cnt;
  104. }
  105. @Override
  106. public Ref next() {
  107. if (idx < cnt)
  108. return list[idx++];
  109. throw new NoSuchElementException();
  110. }
  111. @Override
  112. public void remove() {
  113. throw new UnsupportedOperationException();
  114. }
  115. };
  116. }
  117. /**
  118. * Cast {@code this} as an immutable, standard {@link java.util.List}.
  119. *
  120. * @return {@code this} as an immutable, standard {@link java.util.List}.
  121. */
  122. public final List<Ref> asList() {
  123. final List<Ref> r = Arrays.asList(list).subList(0, cnt);
  124. return Collections.unmodifiableList(r);
  125. }
  126. /**
  127. * Get number of items in this list.
  128. *
  129. * @return number of items in this list.
  130. */
  131. public final int size() {
  132. return cnt;
  133. }
  134. /**
  135. * Get if this list is empty.
  136. *
  137. * @return true if the size of this list is 0.
  138. */
  139. public final boolean isEmpty() {
  140. return cnt == 0;
  141. }
  142. /**
  143. * Locate an entry by name.
  144. *
  145. * @param name
  146. * the name of the reference to find.
  147. * @return the index the reference is at. If the entry is not present
  148. * returns a negative value. The insertion position for the given
  149. * name can be computed from {@code -(index + 1)}.
  150. */
  151. public final int find(String name) {
  152. int high = cnt;
  153. if (high == 0)
  154. return -1;
  155. int low = 0;
  156. do {
  157. final int mid = (low + high) >>> 1;
  158. final int cmp = RefComparator.compareTo(list[mid], name);
  159. if (cmp < 0)
  160. low = mid + 1;
  161. else if (cmp == 0)
  162. return mid;
  163. else
  164. high = mid;
  165. } while (low < high);
  166. return -(low + 1);
  167. }
  168. /**
  169. * Determine if a reference is present.
  170. *
  171. * @param name
  172. * name of the reference to find.
  173. * @return true if the reference is present; false if it is not.
  174. */
  175. public final boolean contains(String name) {
  176. return 0 <= find(name);
  177. }
  178. /**
  179. * Get a reference object by name.
  180. *
  181. * @param name
  182. * the name of the reference.
  183. * @return the reference object; null if it does not exist in this list.
  184. */
  185. public final T get(String name) {
  186. int idx = find(name);
  187. return 0 <= idx ? get(idx) : null;
  188. }
  189. /**
  190. * Get the reference at a particular index.
  191. *
  192. * @param idx
  193. * the index to obtain. Must be {@code 0 <= idx < size()}.
  194. * @return the reference value, never null.
  195. */
  196. @SuppressWarnings("unchecked")
  197. public final T get(int idx) {
  198. return (T) list[idx];
  199. }
  200. /**
  201. * Obtain a builder initialized with the first {@code n} elements.
  202. * <p>
  203. * Copies the first {@code n} elements from this list into a new builder,
  204. * which can be used by the caller to add additional elements.
  205. *
  206. * @param n
  207. * the number of elements to copy.
  208. * @return a new builder with the first {@code n} elements already added.
  209. */
  210. public final Builder<T> copy(int n) {
  211. Builder<T> r = new Builder<>(Math.max(16, n));
  212. r.addAll(list, 0, n);
  213. return r;
  214. }
  215. /**
  216. * Obtain a new copy of the list after changing one element.
  217. * <p>
  218. * This list instance is not affected by the replacement. Because this
  219. * method copies the entire list, it runs in O(N) time.
  220. *
  221. * @param idx
  222. * index of the element to change.
  223. * @param ref
  224. * the new value, must not be null.
  225. * @return copy of this list, after replacing {@code idx} with {@code ref} .
  226. */
  227. public final RefList<T> set(int idx, T ref) {
  228. Ref[] newList = new Ref[cnt];
  229. System.arraycopy(list, 0, newList, 0, cnt);
  230. newList[idx] = ref;
  231. return new RefList<>(newList, cnt);
  232. }
  233. /**
  234. * Add an item at a specific index.
  235. * <p>
  236. * This list instance is not affected by the addition. Because this method
  237. * copies the entire list, it runs in O(N) time.
  238. *
  239. * @param idx
  240. * position to add the item at. If negative the method assumes it
  241. * was a direct return value from {@link #find(String)} and will
  242. * adjust it to the correct position.
  243. * @param ref
  244. * the new reference to insert.
  245. * @return copy of this list, after making space for and adding {@code ref}.
  246. */
  247. public final RefList<T> add(int idx, T ref) {
  248. if (idx < 0)
  249. idx = -(idx + 1);
  250. Ref[] newList = new Ref[cnt + 1];
  251. if (0 < idx)
  252. System.arraycopy(list, 0, newList, 0, idx);
  253. newList[idx] = ref;
  254. if (idx < cnt)
  255. System.arraycopy(list, idx, newList, idx + 1, cnt - idx);
  256. return new RefList<>(newList, cnt + 1);
  257. }
  258. /**
  259. * Remove an item at a specific index.
  260. * <p>
  261. * This list instance is not affected by the addition. Because this method
  262. * copies the entire list, it runs in O(N) time.
  263. *
  264. * @param idx
  265. * position to remove the item from.
  266. * @return copy of this list, after making removing the item at {@code idx}.
  267. */
  268. public final RefList<T> remove(int idx) {
  269. if (cnt == 1)
  270. return emptyList();
  271. Ref[] newList = new Ref[cnt - 1];
  272. if (0 < idx)
  273. System.arraycopy(list, 0, newList, 0, idx);
  274. if (idx + 1 < cnt)
  275. System.arraycopy(list, idx + 1, newList, idx, cnt - (idx + 1));
  276. return new RefList<>(newList, cnt - 1);
  277. }
  278. /**
  279. * Store a reference, adding or replacing as necessary.
  280. * <p>
  281. * This list instance is not affected by the store. The correct position is
  282. * determined, and the item is added if missing, or replaced if existing.
  283. * Because this method copies the entire list, it runs in O(N + log N) time.
  284. *
  285. * @param ref
  286. * the reference to store.
  287. * @return copy of this list, after performing the addition or replacement.
  288. */
  289. public final RefList<T> put(T ref) {
  290. int idx = find(ref.getName());
  291. if (0 <= idx)
  292. return set(idx, ref);
  293. return add(idx, ref);
  294. }
  295. /** {@inheritDoc} */
  296. @Override
  297. public String toString() {
  298. StringBuilder r = new StringBuilder();
  299. r.append('[');
  300. if (cnt > 0) {
  301. r.append(list[0]);
  302. for (int i = 1; i < cnt; i++) {
  303. r.append(", "); //$NON-NLS-1$
  304. r.append(list[i]);
  305. }
  306. }
  307. r.append(']');
  308. return r.toString();
  309. }
  310. /**
  311. * Create a {@link Collector} for {@link Ref}.
  312. *
  313. * @param mergeFunction
  314. * if specified the result will be sorted and deduped.
  315. * @return {@link Collector} for {@link Ref}
  316. * @since 5.4
  317. */
  318. public static <T extends Ref> Collector<T, ?, RefList<T>> toRefList(
  319. @Nullable BinaryOperator<T> mergeFunction) {
  320. return Collector.of(
  321. () -> new Builder<>(),
  322. Builder<T>::add, (b1, b2) -> {
  323. Builder<T> b = new Builder<>();
  324. b.addAll(b1);
  325. b.addAll(b2);
  326. return b;
  327. }, (b) -> {
  328. if (mergeFunction != null) {
  329. b.sort();
  330. b.dedupe(mergeFunction);
  331. }
  332. return b.toRefList();
  333. });
  334. }
  335. /**
  336. * Builder to facilitate fast construction of an immutable RefList.
  337. *
  338. * @param <T>
  339. * type of reference being stored.
  340. */
  341. public static class Builder<T extends Ref> {
  342. private Ref[] list;
  343. private int size;
  344. /** Create an empty list ready for items to be added. */
  345. public Builder() {
  346. this(16);
  347. }
  348. /**
  349. * Create an empty list with at least the specified capacity.
  350. *
  351. * @param capacity
  352. * the new capacity; if zero or negative, behavior is the same as
  353. * {@link #Builder()}.
  354. */
  355. public Builder(int capacity) {
  356. list = new Ref[Math.max(capacity, 16)];
  357. }
  358. /** @return number of items in this builder's internal collection. */
  359. public int size() {
  360. return size;
  361. }
  362. /**
  363. * Get the reference at a particular index.
  364. *
  365. * @param idx
  366. * the index to obtain. Must be {@code 0 <= idx < size()}.
  367. * @return the reference value, never null.
  368. */
  369. @SuppressWarnings("unchecked")
  370. public T get(int idx) {
  371. return (T) list[idx];
  372. }
  373. /**
  374. * Remove an item at a specific index.
  375. *
  376. * @param idx
  377. * position to remove the item from.
  378. */
  379. public void remove(int idx) {
  380. System.arraycopy(list, idx + 1, list, idx, size - (idx + 1));
  381. size--;
  382. }
  383. /**
  384. * Add the reference to the end of the array.
  385. * <p>
  386. * References must be added in sort order, or the array must be sorted
  387. * after additions are complete using {@link #sort()}.
  388. *
  389. * @param ref
  390. */
  391. public void add(T ref) {
  392. if (list.length == size) {
  393. Ref[] n = new Ref[size * 2];
  394. System.arraycopy(list, 0, n, 0, size);
  395. list = n;
  396. }
  397. list[size++] = ref;
  398. }
  399. /**
  400. * Add all items from another builder.
  401. *
  402. * @param other
  403. * @since 5.4
  404. */
  405. public void addAll(Builder other) {
  406. addAll(other.list, 0, other.size);
  407. }
  408. /**
  409. * Add all items from a source array.
  410. * <p>
  411. * References must be added in sort order, or the array must be sorted
  412. * after additions are complete using {@link #sort()}.
  413. *
  414. * @param src
  415. * the source array.
  416. * @param off
  417. * position within {@code src} to start copying from.
  418. * @param cnt
  419. * number of items to copy from {@code src}.
  420. */
  421. public void addAll(Ref[] src, int off, int cnt) {
  422. if (list.length < size + cnt) {
  423. Ref[] n = new Ref[Math.max(size * 2, size + cnt)];
  424. System.arraycopy(list, 0, n, 0, size);
  425. list = n;
  426. }
  427. System.arraycopy(src, off, list, size, cnt);
  428. size += cnt;
  429. }
  430. /**
  431. * Replace a single existing element.
  432. *
  433. * @param idx
  434. * index, must have already been added previously.
  435. * @param ref
  436. * the new reference.
  437. */
  438. public void set(int idx, T ref) {
  439. list[idx] = ref;
  440. }
  441. /** Sort the list's backing array in-place. */
  442. public void sort() {
  443. Arrays.sort(list, 0, size, RefComparator.INSTANCE);
  444. }
  445. /**
  446. * Dedupe the refs in place. Must be called after {@link #sort}.
  447. *
  448. * @param mergeFunction
  449. */
  450. @SuppressWarnings("unchecked")
  451. void dedupe(BinaryOperator<T> mergeFunction) {
  452. if (size == 0) {
  453. return;
  454. }
  455. int lastElement = 0;
  456. for (int i = 1; i < size; i++) {
  457. if (RefComparator.INSTANCE.compare(list[lastElement],
  458. list[i]) == 0) {
  459. list[lastElement] = mergeFunction
  460. .apply((T) list[lastElement], (T) list[i]);
  461. } else {
  462. list[lastElement + 1] = list[i];
  463. lastElement++;
  464. }
  465. }
  466. size = lastElement + 1;
  467. Arrays.fill(list, size, list.length, null);
  468. }
  469. /** @return an unmodifiable list using this collection's backing array. */
  470. public RefList<T> toRefList() {
  471. return new RefList<>(list, size);
  472. }
  473. @Override
  474. public String toString() {
  475. return toRefList().toString();
  476. }
  477. }
  478. }