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