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