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