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