001/*
002 * Copyright (C) 2017 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.primitives;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019
020import com.google.common.annotations.GwtCompatible;
021import com.google.common.base.Preconditions;
022import com.google.errorprone.annotations.CanIgnoreReturnValue;
023import com.google.errorprone.annotations.Immutable;
024import java.io.Serializable;
025import java.util.AbstractList;
026import java.util.Arrays;
027import java.util.Collection;
028import java.util.List;
029import java.util.RandomAccess;
030import java.util.Spliterator;
031import java.util.Spliterators;
032import java.util.function.IntConsumer;
033import java.util.stream.IntStream;
034import org.jspecify.annotations.Nullable;
035
036/**
037 * An immutable array of {@code int} values, with an API resembling {@link List}.
038 *
039 * <p>Advantages compared to {@code int[]}:
040 *
041 * <ul>
042 *   <li>All the many well-known advantages of immutability (read <i>Effective Java</i>, third
043 *       edition, Item 17).
044 *   <li>Has the value-based (not identity-based) {@link #equals}, {@link #hashCode}, and {@link
045 *       #toString} behavior you expect.
046 *   <li>Offers useful operations beyond just {@code get} and {@code length}, so you don't have to
047 *       hunt through classes like {@link Arrays} and {@link Ints} for them.
048 *   <li>Supports a copy-free {@link #subArray} view, so methods that accept this type don't need to
049 *       add overloads that accept start and end indexes.
050 *   <li>Can be streamed without "breaking the chain": {@code foo.getBarInts().stream()...}.
051 *   <li>Access to all collection-based utilities via {@link #asList} (though at the cost of
052 *       allocating garbage).
053 * </ul>
054 *
055 * <p>Disadvantages compared to {@code int[]}:
056 *
057 * <ul>
058 *   <li>Memory footprint has a fixed overhead (about 24 bytes per instance).
059 *   <li><i>Some</i> construction use cases force the data to be copied (though several construction
060 *       APIs are offered that don't).
061 *   <li>Can't be passed directly to methods that expect {@code int[]} (though the most common
062 *       utilities do have replacements here).
063 *   <li>Dependency on {@code com.google.common} / Guava.
064 * </ul>
065 *
066 * <p>Advantages compared to {@link com.google.common.collect.ImmutableList ImmutableList}{@code
067 * <Integer>}:
068 *
069 * <ul>
070 *   <li>Improved memory compactness and locality.
071 *   <li>Can be queried without allocating garbage.
072 *   <li>Access to {@code IntStream} features (like {@link IntStream#sum}) using {@code stream()}
073 *       instead of the awkward {@code stream().mapToInt(v -> v)}.
074 * </ul>
075 *
076 * <p>Disadvantages compared to {@code ImmutableList<Integer>}:
077 *
078 * <ul>
079 *   <li>Can't be passed directly to methods that expect {@code Iterable}, {@code Collection}, or
080 *       {@code List} (though the most common utilities do have replacements here, and there is a
081 *       lazy {@link #asList} view).
082 * </ul>
083 *
084 * @since 22.0
085 */
086@GwtCompatible
087@Immutable
088public final class ImmutableIntArray implements Serializable {
089  private static final ImmutableIntArray EMPTY = new ImmutableIntArray(new int[0]);
090
091  /** Returns the empty array. */
092  public static ImmutableIntArray of() {
093    return EMPTY;
094  }
095
096  /** Returns an immutable array containing a single value. */
097  public static ImmutableIntArray of(int e0) {
098    return new ImmutableIntArray(new int[] {e0});
099  }
100
101  /** Returns an immutable array containing the given values, in order. */
102  public static ImmutableIntArray of(int e0, int e1) {
103    return new ImmutableIntArray(new int[] {e0, e1});
104  }
105
106  /** Returns an immutable array containing the given values, in order. */
107  public static ImmutableIntArray of(int e0, int e1, int e2) {
108    return new ImmutableIntArray(new int[] {e0, e1, e2});
109  }
110
111  /** Returns an immutable array containing the given values, in order. */
112  public static ImmutableIntArray of(int e0, int e1, int e2, int e3) {
113    return new ImmutableIntArray(new int[] {e0, e1, e2, e3});
114  }
115
116  /** Returns an immutable array containing the given values, in order. */
117  public static ImmutableIntArray of(int e0, int e1, int e2, int e3, int e4) {
118    return new ImmutableIntArray(new int[] {e0, e1, e2, e3, e4});
119  }
120
121  /** Returns an immutable array containing the given values, in order. */
122  public static ImmutableIntArray of(int e0, int e1, int e2, int e3, int e4, int e5) {
123    return new ImmutableIntArray(new int[] {e0, e1, e2, e3, e4, e5});
124  }
125
126  // TODO(kevinb): go up to 11?
127
128  /**
129   * Returns an immutable array containing the given values, in order.
130   *
131   * <p>The array {@code rest} must not be longer than {@code Integer.MAX_VALUE - 1}.
132   */
133  // Use (first, rest) so that `of(someIntArray)` won't compile (they should use copyOf), which is
134  // okay since we have to copy the just-created array anyway.
135  public static ImmutableIntArray of(int first, int... rest) {
136    checkArgument(
137        rest.length <= Integer.MAX_VALUE - 1, "the total number of elements must fit in an int");
138    int[] array = new int[rest.length + 1];
139    array[0] = first;
140    System.arraycopy(rest, 0, array, 1, rest.length);
141    return new ImmutableIntArray(array);
142  }
143
144  /** Returns an immutable array containing the given values, in order. */
145  public static ImmutableIntArray copyOf(int[] values) {
146    return values.length == 0 ? EMPTY : new ImmutableIntArray(Arrays.copyOf(values, values.length));
147  }
148
149  /** Returns an immutable array containing the given values, in order. */
150  public static ImmutableIntArray copyOf(Collection<Integer> values) {
151    return values.isEmpty() ? EMPTY : new ImmutableIntArray(Ints.toArray(values));
152  }
153
154  /**
155   * Returns an immutable array containing the given values, in order.
156   *
157   * <p><b>Performance note:</b> this method delegates to {@link #copyOf(Collection)} if {@code
158   * values} is a {@link Collection}. Otherwise it creates a {@link #builder} and uses {@link
159   * Builder#addAll(Iterable)}, with all the performance implications associated with that.
160   */
161  public static ImmutableIntArray copyOf(Iterable<Integer> values) {
162    if (values instanceof Collection) {
163      return copyOf((Collection<Integer>) values);
164    }
165    return builder().addAll(values).build();
166  }
167
168  /**
169   * Returns an immutable array containing all the values from {@code stream}, in order.
170   *
171   * @since 22.0 (but only since 33.4.0 in the Android flavor)
172   */
173  public static ImmutableIntArray copyOf(IntStream stream) {
174    // Note this uses very different growth behavior from copyOf(Iterable) and the builder.
175    int[] array = stream.toArray();
176    return (array.length == 0) ? EMPTY : new ImmutableIntArray(array);
177  }
178
179  /**
180   * Returns a new, empty builder for {@link ImmutableIntArray} instances, sized to hold up to
181   * {@code initialCapacity} values without resizing. The returned builder is not thread-safe.
182   *
183   * <p><b>Performance note:</b> When feasible, {@code initialCapacity} should be the exact number
184   * of values that will be added, if that knowledge is readily available. It is better to guess a
185   * value slightly too high than slightly too low. If the value is not exact, the {@link
186   * ImmutableIntArray} that is built will very likely occupy more memory than strictly necessary;
187   * to trim memory usage, build using {@code builder.build().trimmed()}.
188   */
189  public static Builder builder(int initialCapacity) {
190    checkArgument(initialCapacity >= 0, "Invalid initialCapacity: %s", initialCapacity);
191    return new Builder(initialCapacity);
192  }
193
194  /**
195   * Returns a new, empty builder for {@link ImmutableIntArray} instances, with a default initial
196   * capacity. The returned builder is not thread-safe.
197   *
198   * <p><b>Performance note:</b> The {@link ImmutableIntArray} that is built will very likely occupy
199   * more memory than necessary; to trim memory usage, build using {@code
200   * builder.build().trimmed()}.
201   */
202  public static Builder builder() {
203    return new Builder(10);
204  }
205
206  /**
207   * A builder for {@link ImmutableIntArray} instances; obtained using {@link
208   * ImmutableIntArray#builder}.
209   */
210  public static final class Builder {
211    private int[] array;
212    private int count = 0; // <= array.length
213
214    Builder(int initialCapacity) {
215      array = new int[initialCapacity];
216    }
217
218    /**
219     * Appends {@code value} to the end of the values the built {@link ImmutableIntArray} will
220     * contain.
221     */
222    @CanIgnoreReturnValue
223    public Builder add(int value) {
224      ensureRoomFor(1);
225      array[count] = value;
226      count += 1;
227      return this;
228    }
229
230    /**
231     * Appends {@code values}, in order, to the end of the values the built {@link
232     * ImmutableIntArray} will contain.
233     */
234    @CanIgnoreReturnValue
235    public Builder addAll(int[] values) {
236      ensureRoomFor(values.length);
237      System.arraycopy(values, 0, array, count, values.length);
238      count += values.length;
239      return this;
240    }
241
242    /**
243     * Appends {@code values}, in order, to the end of the values the built {@link
244     * ImmutableIntArray} will contain.
245     */
246    @CanIgnoreReturnValue
247    public Builder addAll(Iterable<Integer> values) {
248      if (values instanceof Collection) {
249        return addAll((Collection<Integer>) values);
250      }
251      for (Integer value : values) {
252        add(value);
253      }
254      return this;
255    }
256
257    /**
258     * Appends {@code values}, in order, to the end of the values the built {@link
259     * ImmutableIntArray} will contain.
260     */
261    @CanIgnoreReturnValue
262    public Builder addAll(Collection<Integer> values) {
263      ensureRoomFor(values.size());
264      for (Integer value : values) {
265        array[count++] = value;
266      }
267      return this;
268    }
269
270    /**
271     * Appends all values from {@code stream}, in order, to the end of the values the built {@link
272     * ImmutableIntArray} will contain.
273     *
274     * @since 22.0 (but only since 33.4.0 in the Android flavor)
275     */
276    @CanIgnoreReturnValue
277    public Builder addAll(IntStream stream) {
278      Spliterator.OfInt spliterator = stream.spliterator();
279      long size = spliterator.getExactSizeIfKnown();
280      if (size > 0) { // known *and* nonempty
281        ensureRoomFor(Ints.saturatedCast(size));
282      }
283      spliterator.forEachRemaining((IntConsumer) this::add);
284      return this;
285    }
286
287    /**
288     * Appends {@code values}, in order, to the end of the values the built {@link
289     * ImmutableIntArray} will contain.
290     */
291    @CanIgnoreReturnValue
292    public Builder addAll(ImmutableIntArray values) {
293      ensureRoomFor(values.length());
294      System.arraycopy(values.array, values.start, array, count, values.length());
295      count += values.length();
296      return this;
297    }
298
299    private void ensureRoomFor(int numberToAdd) {
300      int newCount = count + numberToAdd; // TODO(kevinb): check overflow now?
301      if (newCount > array.length) {
302        array = Arrays.copyOf(array, expandedCapacity(array.length, newCount));
303      }
304    }
305
306    // Unfortunately this is pasted from ImmutableCollection.Builder.
307    private static int expandedCapacity(int oldCapacity, int minCapacity) {
308      if (minCapacity < 0) {
309        throw new AssertionError("cannot store more than MAX_VALUE elements");
310      }
311      // careful of overflow!
312      int newCapacity = oldCapacity + (oldCapacity >> 1) + 1;
313      if (newCapacity < minCapacity) {
314        newCapacity = Integer.highestOneBit(minCapacity - 1) << 1;
315      }
316      if (newCapacity < 0) {
317        newCapacity = Integer.MAX_VALUE; // guaranteed to be >= newCapacity
318      }
319      return newCapacity;
320    }
321
322    /**
323     * Returns a new immutable array. The builder can continue to be used after this call, to append
324     * more values and build again.
325     *
326     * <p><b>Performance note:</b> the returned array is backed by the same array as the builder, so
327     * no data is copied as part of this step, but this may occupy more memory than strictly
328     * necessary. To copy the data to a right-sized backing array, use {@code .build().trimmed()}.
329     */
330    public ImmutableIntArray build() {
331      return count == 0 ? EMPTY : new ImmutableIntArray(array, 0, count);
332    }
333  }
334
335  // Instance stuff here
336
337  // The array is never mutated after storing in this field and the construction strategies ensure
338  // it doesn't escape this class
339  @SuppressWarnings("Immutable")
340  private final int[] array;
341
342  /*
343   * TODO(kevinb): evaluate the trade-offs of going bimorphic to save these two fields from most
344   * instances. Note that the instances that would get smaller are the right set to care about
345   * optimizing, because the rest have the option of calling `trimmed`.
346   */
347
348  private final transient int start; // it happens that we only serialize instances where this is 0
349  private final int end; // exclusive
350
351  private ImmutableIntArray(int[] array) {
352    this(array, 0, array.length);
353  }
354
355  private ImmutableIntArray(int[] array, int start, int end) {
356    this.array = array;
357    this.start = start;
358    this.end = end;
359  }
360
361  /** Returns the number of values in this array. */
362  public int length() {
363    return end - start;
364  }
365
366  /** Returns {@code true} if there are no values in this array ({@link #length} is zero). */
367  public boolean isEmpty() {
368    return end == start;
369  }
370
371  /**
372   * Returns the {@code int} value present at the given index.
373   *
374   * @throws IndexOutOfBoundsException if {@code index} is negative, or greater than or equal to
375   *     {@link #length}
376   */
377  public int get(int index) {
378    Preconditions.checkElementIndex(index, length());
379    return array[start + index];
380  }
381
382  /**
383   * Returns the smallest index for which {@link #get} returns {@code target}, or {@code -1} if no
384   * such index exists. Equivalent to {@code asList().indexOf(target)}.
385   */
386  public int indexOf(int target) {
387    for (int i = start; i < end; i++) {
388      if (array[i] == target) {
389        return i - start;
390      }
391    }
392    return -1;
393  }
394
395  /**
396   * Returns the largest index for which {@link #get} returns {@code target}, or {@code -1} if no
397   * such index exists. Equivalent to {@code asList().lastIndexOf(target)}.
398   */
399  public int lastIndexOf(int target) {
400    for (int i = end - 1; i >= start; i--) {
401      if (array[i] == target) {
402        return i - start;
403      }
404    }
405    return -1;
406  }
407
408  /**
409   * Returns {@code true} if {@code target} is present at any index in this array. Equivalent to
410   * {@code asList().contains(target)}.
411   */
412  public boolean contains(int target) {
413    return indexOf(target) >= 0;
414  }
415
416  /**
417   * Invokes {@code consumer} for each value contained in this array, in order.
418   *
419   * @since 22.0 (but only since 33.4.0 in the Android flavor)
420   */
421  public void forEach(IntConsumer consumer) {
422    checkNotNull(consumer);
423    for (int i = start; i < end; i++) {
424      consumer.accept(array[i]);
425    }
426  }
427
428  /**
429   * Returns a stream over the values in this array, in order.
430   *
431   * @since 22.0 (but only since 33.4.0 in the Android flavor)
432   */
433  public IntStream stream() {
434    return Arrays.stream(array, start, end);
435  }
436
437  /** Returns a new, mutable copy of this array's values, as a primitive {@code int[]}. */
438  public int[] toArray() {
439    return Arrays.copyOfRange(array, start, end);
440  }
441
442  /**
443   * Returns a new immutable array containing the values in the specified range.
444   *
445   * <p><b>Performance note:</b> The returned array has the same full memory footprint as this one
446   * does (no actual copying is performed). To reduce memory usage, use {@code subArray(start,
447   * end).trimmed()}.
448   */
449  public ImmutableIntArray subArray(int startIndex, int endIndex) {
450    Preconditions.checkPositionIndexes(startIndex, endIndex, length());
451    return startIndex == endIndex
452        ? EMPTY
453        : new ImmutableIntArray(array, start + startIndex, start + endIndex);
454  }
455
456  /*
457   * We declare this as package-private, rather than private, to avoid generating a synthetic
458   * accessor method (under -target 8) that would lack the Android flavor's @IgnoreJRERequirement.
459   */
460  Spliterator.OfInt spliterator() {
461    return Spliterators.spliterator(array, start, end, Spliterator.IMMUTABLE | Spliterator.ORDERED);
462  }
463
464  /**
465   * Returns an immutable <i>view</i> of this array's values as a {@code List}; note that {@code
466   * int} values are boxed into {@link Integer} instances on demand, which can be very expensive.
467   * The returned list should be used once and discarded. For any usages beyond that, pass the
468   * returned list to {@link com.google.common.collect.ImmutableList#copyOf(Collection)
469   * ImmutableList.copyOf} and use that list instead.
470   */
471  public List<Integer> asList() {
472    /*
473     * Typically we cache this kind of thing, but much repeated use of this view is a performance
474     * anti-pattern anyway. If we cache, then everyone pays a price in memory footprint even if
475     * they never use this method.
476     */
477    return new AsList(this);
478  }
479
480  static class AsList extends AbstractList<Integer> implements RandomAccess, Serializable {
481    private final ImmutableIntArray parent;
482
483    private AsList(ImmutableIntArray parent) {
484      this.parent = parent;
485    }
486
487    // inherit: isEmpty, containsAll, toArray x2, iterator, listIterator, stream, forEach, mutations
488
489    @Override
490    public int size() {
491      return parent.length();
492    }
493
494    @Override
495    public Integer get(int index) {
496      return parent.get(index);
497    }
498
499    @Override
500    public boolean contains(@Nullable Object target) {
501      return indexOf(target) >= 0;
502    }
503
504    @Override
505    public int indexOf(@Nullable Object target) {
506      return target instanceof Integer ? parent.indexOf((Integer) target) : -1;
507    }
508
509    @Override
510    public int lastIndexOf(@Nullable Object target) {
511      return target instanceof Integer ? parent.lastIndexOf((Integer) target) : -1;
512    }
513
514    @Override
515    public List<Integer> subList(int fromIndex, int toIndex) {
516      return parent.subArray(fromIndex, toIndex).asList();
517    }
518
519    // The default List spliterator is not efficiently splittable
520    @Override
521    public Spliterator<Integer> spliterator() {
522      return parent.spliterator();
523    }
524
525    @Override
526    public boolean equals(@Nullable Object object) {
527      if (object instanceof AsList) {
528        AsList that = (AsList) object;
529        return this.parent.equals(that.parent);
530      }
531      // We could delegate to super now but it would still box too much
532      if (!(object instanceof List)) {
533        return false;
534      }
535      List<?> that = (List<?>) object;
536      if (this.size() != that.size()) {
537        return false;
538      }
539      int i = parent.start;
540      // Since `that` is very likely RandomAccess we could avoid allocating this iterator...
541      for (Object element : that) {
542        if (!(element instanceof Integer) || parent.array[i++] != (Integer) element) {
543          return false;
544        }
545      }
546      return true;
547    }
548
549    // Because we happen to use the same formula. If that changes, just don't override this.
550    @Override
551    public int hashCode() {
552      return parent.hashCode();
553    }
554
555    @Override
556    public String toString() {
557      return parent.toString();
558    }
559  }
560
561  /**
562   * Returns {@code true} if {@code object} is an {@code ImmutableIntArray} containing the same
563   * values as this one, in the same order.
564   */
565  @Override
566  public boolean equals(@Nullable Object object) {
567    if (object == this) {
568      return true;
569    }
570    if (!(object instanceof ImmutableIntArray)) {
571      return false;
572    }
573    ImmutableIntArray that = (ImmutableIntArray) object;
574    if (this.length() != that.length()) {
575      return false;
576    }
577    for (int i = 0; i < length(); i++) {
578      if (this.get(i) != that.get(i)) {
579        return false;
580      }
581    }
582    return true;
583  }
584
585  /** Returns an unspecified hash code for the contents of this immutable array. */
586  @Override
587  public int hashCode() {
588    int hash = 1;
589    for (int i = start; i < end; i++) {
590      hash *= 31;
591      hash += Ints.hashCode(array[i]);
592    }
593    return hash;
594  }
595
596  /**
597   * Returns a string representation of this array in the same form as {@link
598   * Arrays#toString(int[])}, for example {@code "[1, 2, 3]"}.
599   */
600  @Override
601  public String toString() {
602    if (isEmpty()) {
603      return "[]";
604    }
605    StringBuilder builder = new StringBuilder(length() * 5); // rough estimate is fine
606    builder.append('[').append(array[start]);
607
608    for (int i = start + 1; i < end; i++) {
609      builder.append(", ").append(array[i]);
610    }
611    builder.append(']');
612    return builder.toString();
613  }
614
615  /**
616   * Returns an immutable array containing the same values as {@code this} array. This is logically
617   * a no-op, and in some circumstances {@code this} itself is returned. However, if this instance
618   * is a {@link #subArray} view of a larger array, this method will copy only the appropriate range
619   * of values, resulting in an equivalent array with a smaller memory footprint.
620   */
621  public ImmutableIntArray trimmed() {
622    return isPartialView() ? new ImmutableIntArray(toArray()) : this;
623  }
624
625  private boolean isPartialView() {
626    return start > 0 || end < array.length;
627  }
628
629  Object writeReplace() {
630    return trimmed();
631  }
632
633  Object readResolve() {
634    return isEmpty() ? EMPTY : this;
635  }
636}