001/*
002 * Copyright (C) 2008 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.checkElementIndex;
019import static com.google.common.base.Preconditions.checkNotNull;
020import static com.google.common.base.Preconditions.checkPositionIndexes;
021import static com.google.common.base.Strings.lenientFormat;
022import static java.lang.Double.NEGATIVE_INFINITY;
023import static java.lang.Double.POSITIVE_INFINITY;
024
025import com.google.common.annotations.GwtCompatible;
026import com.google.common.annotations.GwtIncompatible;
027import com.google.common.base.Converter;
028import com.google.errorprone.annotations.InlineMe;
029import java.io.Serializable;
030import java.util.AbstractList;
031import java.util.Arrays;
032import java.util.Collection;
033import java.util.Collections;
034import java.util.Comparator;
035import java.util.List;
036import java.util.RandomAccess;
037import java.util.Spliterator;
038import java.util.Spliterators;
039import javax.annotation.CheckForNull;
040
041/**
042 * Static utility methods pertaining to {@code double} primitives, that are not already found in
043 * either {@link Double} or {@link Arrays}.
044 *
045 * <p>See the Guava User Guide article on <a
046 * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>.
047 *
048 * @author Kevin Bourrillion
049 * @since 1.0
050 */
051@GwtCompatible(emulated = true)
052@ElementTypesAreNonnullByDefault
053public final class Doubles extends DoublesMethodsForWeb {
054  private Doubles() {}
055
056  /**
057   * The number of bytes required to represent a primitive {@code double} value.
058   *
059   * <p><b>Java 8+ users:</b> use {@link Double#BYTES} instead.
060   *
061   * @since 10.0
062   */
063  public static final int BYTES = Double.SIZE / Byte.SIZE;
064
065  /**
066   * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Double)
067   * value).hashCode()}.
068   *
069   * <p><b>Java 8+ users:</b> use {@link Double#hashCode(double)} instead.
070   *
071   * @param value a primitive {@code double} value
072   * @return a hash code for the value
073   */
074  public static int hashCode(double value) {
075    return ((Double) value).hashCode();
076    // TODO(kevinb): do it this way when we can (GWT problem):
077    // long bits = Double.doubleToLongBits(value);
078    // return (int) (bits ^ (bits >>> 32));
079  }
080
081  /**
082   * Compares the two specified {@code double} values. The sign of the value returned is the same as
083   * that of <code>((Double) a).{@linkplain Double#compareTo compareTo}(b)</code>. As with that
084   * method, {@code NaN} is treated as greater than all other values, and {@code 0.0 > -0.0}.
085   *
086   * <p><b>Note:</b> this method simply delegates to the JDK method {@link Double#compare}. It is
087   * provided for consistency with the other primitive types, whose compare methods were not added
088   * to the JDK until JDK 7.
089   *
090   * @param a the first {@code double} to compare
091   * @param b the second {@code double} to compare
092   * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is
093   *     greater than {@code b}; or zero if they are equal
094   */
095  @InlineMe(replacement = "Double.compare(a, b)")
096  public static int compare(double a, double b) {
097    return Double.compare(a, b);
098  }
099
100  /**
101   * Returns {@code true} if {@code value} represents a real number. This is equivalent to, but not
102   * necessarily implemented as, {@code !(Double.isInfinite(value) || Double.isNaN(value))}.
103   *
104   * <p><b>Java 8+ users:</b> use {@link Double#isFinite(double)} instead.
105   *
106   * @since 10.0
107   */
108  public static boolean isFinite(double value) {
109    return NEGATIVE_INFINITY < value && value < POSITIVE_INFINITY;
110  }
111
112  /**
113   * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}. Note
114   * that this always returns {@code false} when {@code target} is {@code NaN}.
115   *
116   * @param array an array of {@code double} values, possibly empty
117   * @param target a primitive {@code double} value
118   * @return {@code true} if {@code array[i] == target} for some value of {@code i}
119   */
120  public static boolean contains(double[] array, double target) {
121    for (double value : array) {
122      if (value == target) {
123        return true;
124      }
125    }
126    return false;
127  }
128
129  /**
130   * Returns the index of the first appearance of the value {@code target} in {@code array}. Note
131   * that this always returns {@code -1} when {@code target} is {@code NaN}.
132   *
133   * @param array an array of {@code double} values, possibly empty
134   * @param target a primitive {@code double} value
135   * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no
136   *     such index exists.
137   */
138  public static int indexOf(double[] array, double target) {
139    return indexOf(array, target, 0, array.length);
140  }
141
142  // TODO(kevinb): consider making this public
143  private static int indexOf(double[] array, double target, int start, int end) {
144    for (int i = start; i < end; i++) {
145      if (array[i] == target) {
146        return i;
147      }
148    }
149    return -1;
150  }
151
152  /**
153   * Returns the start position of the first occurrence of the specified {@code target} within
154   * {@code array}, or {@code -1} if there is no such occurrence.
155   *
156   * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array,
157   * i, i + target.length)} contains exactly the same elements as {@code target}.
158   *
159   * <p>Note that this always returns {@code -1} when {@code target} contains {@code NaN}.
160   *
161   * @param array the array to search for the sequence {@code target}
162   * @param target the array to search for as a sub-sequence of {@code array}
163   */
164  public static int indexOf(double[] array, double[] target) {
165    checkNotNull(array, "array");
166    checkNotNull(target, "target");
167    if (target.length == 0) {
168      return 0;
169    }
170
171    outer:
172    for (int i = 0; i < array.length - target.length + 1; i++) {
173      for (int j = 0; j < target.length; j++) {
174        if (array[i + j] != target[j]) {
175          continue outer;
176        }
177      }
178      return i;
179    }
180    return -1;
181  }
182
183  /**
184   * Returns the index of the last appearance of the value {@code target} in {@code array}. Note
185   * that this always returns {@code -1} when {@code target} is {@code NaN}.
186   *
187   * @param array an array of {@code double} values, possibly empty
188   * @param target a primitive {@code double} value
189   * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no
190   *     such index exists.
191   */
192  public static int lastIndexOf(double[] array, double target) {
193    return lastIndexOf(array, target, 0, array.length);
194  }
195
196  // TODO(kevinb): consider making this public
197  private static int lastIndexOf(double[] array, double target, int start, int end) {
198    for (int i = end - 1; i >= start; i--) {
199      if (array[i] == target) {
200        return i;
201      }
202    }
203    return -1;
204  }
205
206  /**
207   * Returns the least value present in {@code array}, using the same rules of comparison as {@link
208   * Math#min(double, double)}.
209   *
210   * @param array a <i>nonempty</i> array of {@code double} values
211   * @return the value present in {@code array} that is less than or equal to every other value in
212   *     the array
213   * @throws IllegalArgumentException if {@code array} is empty
214   */
215  @GwtIncompatible(
216      "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.")
217  public static double min(double... array) {
218    checkArgument(array.length > 0);
219    double min = array[0];
220    for (int i = 1; i < array.length; i++) {
221      min = Math.min(min, array[i]);
222    }
223    return min;
224  }
225
226  /**
227   * Returns the greatest value present in {@code array}, using the same rules of comparison as
228   * {@link Math#max(double, double)}.
229   *
230   * @param array a <i>nonempty</i> array of {@code double} values
231   * @return the value present in {@code array} that is greater than or equal to every other value
232   *     in the array
233   * @throws IllegalArgumentException if {@code array} is empty
234   */
235  @GwtIncompatible(
236      "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.")
237  public static double max(double... array) {
238    checkArgument(array.length > 0);
239    double max = array[0];
240    for (int i = 1; i < array.length; i++) {
241      max = Math.max(max, array[i]);
242    }
243    return max;
244  }
245
246  /**
247   * Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}.
248   *
249   * <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned
250   * unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if {@code
251   * value} is greater than {@code max}, {@code max} is returned.
252   *
253   * @param value the {@code double} value to constrain
254   * @param min the lower bound (inclusive) of the range to constrain {@code value} to
255   * @param max the upper bound (inclusive) of the range to constrain {@code value} to
256   * @throws IllegalArgumentException if {@code min > max}
257   * @since 21.0
258   */
259  public static double constrainToRange(double value, double min, double max) {
260    // avoid auto-boxing by not using Preconditions.checkArgument(); see Guava issue 3984
261    // Reject NaN by testing for the good case (min <= max) instead of the bad (min > max).
262    if (min <= max) {
263      return Math.min(Math.max(value, min), max);
264    }
265    throw new IllegalArgumentException(
266        lenientFormat("min (%s) must be less than or equal to max (%s)", min, max));
267  }
268
269  /**
270   * Returns the values from each provided array combined into a single array. For example, {@code
271   * concat(new double[] {a, b}, new double[] {}, new double[] {c}} returns the array {@code {a, b,
272   * c}}.
273   *
274   * @param arrays zero or more {@code double} arrays
275   * @return a single array containing all the values from the source arrays, in order
276   * @throws IllegalArgumentException if the total number of elements in {@code arrays} does not fit
277   *     in an {@code int}
278   */
279  public static double[] concat(double[]... arrays) {
280    long length = 0;
281    for (double[] array : arrays) {
282      length += array.length;
283    }
284    double[] result = new double[checkNoOverflow(length)];
285    int pos = 0;
286    for (double[] array : arrays) {
287      System.arraycopy(array, 0, result, pos, array.length);
288      pos += array.length;
289    }
290    return result;
291  }
292
293  private static int checkNoOverflow(long result) {
294    checkArgument(
295        result == (int) result,
296        "the total number of elements (%s) in the arrays must fit in an int",
297        result);
298    return (int) result;
299  }
300
301  private static final class DoubleConverter extends Converter<String, Double>
302      implements Serializable {
303    static final Converter<String, Double> INSTANCE = new DoubleConverter();
304
305    @Override
306    protected Double doForward(String value) {
307      return Double.valueOf(value);
308    }
309
310    @Override
311    protected String doBackward(Double value) {
312      return value.toString();
313    }
314
315    @Override
316    public String toString() {
317      return "Doubles.stringConverter()";
318    }
319
320    private Object readResolve() {
321      return INSTANCE;
322    }
323
324    private static final long serialVersionUID = 1;
325  }
326
327  /**
328   * Returns a serializable converter object that converts between strings and doubles using {@link
329   * Double#valueOf} and {@link Double#toString()}.
330   *
331   * @since 16.0
332   */
333  public static Converter<String, Double> stringConverter() {
334    return DoubleConverter.INSTANCE;
335  }
336
337  /**
338   * Returns an array containing the same values as {@code array}, but guaranteed to be of a
339   * specified minimum length. If {@code array} already has a length of at least {@code minLength},
340   * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is
341   * returned, containing the values of {@code array}, and zeroes in the remaining places.
342   *
343   * @param array the source array
344   * @param minLength the minimum length the returned array must guarantee
345   * @param padding an extra amount to "grow" the array by if growth is necessary
346   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative
347   * @return an array containing the values of {@code array}, with guaranteed minimum length {@code
348   *     minLength}
349   */
350  public static double[] ensureCapacity(double[] array, int minLength, int padding) {
351    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
352    checkArgument(padding >= 0, "Invalid padding: %s", padding);
353    return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array;
354  }
355
356  /**
357   * Returns a string containing the supplied {@code double} values, converted to strings as
358   * specified by {@link Double#toString(double)}, and separated by {@code separator}. For example,
359   * {@code join("-", 1.0, 2.0, 3.0)} returns the string {@code "1.0-2.0-3.0"}.
360   *
361   * <p>Note that {@link Double#toString(double)} formats {@code double} differently in GWT
362   * sometimes. In the previous example, it returns the string {@code "1-2-3"}.
363   *
364   * @param separator the text that should appear between consecutive values in the resulting string
365   *     (but not at the start or end)
366   * @param array an array of {@code double} values, possibly empty
367   */
368  public static String join(String separator, double... array) {
369    checkNotNull(separator);
370    if (array.length == 0) {
371      return "";
372    }
373
374    // For pre-sizing a builder, just get the right order of magnitude
375    StringBuilder builder = new StringBuilder(array.length * 12);
376    builder.append(array[0]);
377    for (int i = 1; i < array.length; i++) {
378      builder.append(separator).append(array[i]);
379    }
380    return builder.toString();
381  }
382
383  /**
384   * Returns a comparator that compares two {@code double} arrays <a
385   * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it
386   * compares, using {@link #compare(double, double)}), the first pair of values that follow any
387   * common prefix, or when one array is a prefix of the other, treats the shorter array as the
388   * lesser. For example, {@code [] < [1.0] < [1.0, 2.0] < [2.0]}.
389   *
390   * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
391   * support only identity equality), but it is consistent with {@link Arrays#equals(double[],
392   * double[])}.
393   *
394   * @since 2.0
395   */
396  public static Comparator<double[]> lexicographicalComparator() {
397    return LexicographicalComparator.INSTANCE;
398  }
399
400  private enum LexicographicalComparator implements Comparator<double[]> {
401    INSTANCE;
402
403    @Override
404    public int compare(double[] left, double[] right) {
405      int minLength = Math.min(left.length, right.length);
406      for (int i = 0; i < minLength; i++) {
407        int result = Double.compare(left[i], right[i]);
408        if (result != 0) {
409          return result;
410        }
411      }
412      return left.length - right.length;
413    }
414
415    @Override
416    public String toString() {
417      return "Doubles.lexicographicalComparator()";
418    }
419  }
420
421  /**
422   * Sorts the elements of {@code array} in descending order.
423   *
424   * <p>Note that this method uses the total order imposed by {@link Double#compare}, which treats
425   * all NaN values as equal and 0.0 as greater than -0.0.
426   *
427   * @since 23.1
428   */
429  public static void sortDescending(double[] array) {
430    checkNotNull(array);
431    sortDescending(array, 0, array.length);
432  }
433
434  /**
435   * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
436   * exclusive in descending order.
437   *
438   * <p>Note that this method uses the total order imposed by {@link Double#compare}, which treats
439   * all NaN values as equal and 0.0 as greater than -0.0.
440   *
441   * @since 23.1
442   */
443  public static void sortDescending(double[] array, int fromIndex, int toIndex) {
444    checkNotNull(array);
445    checkPositionIndexes(fromIndex, toIndex, array.length);
446    Arrays.sort(array, fromIndex, toIndex);
447    reverse(array, fromIndex, toIndex);
448  }
449
450  /**
451   * Reverses the elements of {@code array}. This is equivalent to {@code
452   * Collections.reverse(Doubles.asList(array))}, but is likely to be more efficient.
453   *
454   * @since 23.1
455   */
456  public static void reverse(double[] array) {
457    checkNotNull(array);
458    reverse(array, 0, array.length);
459  }
460
461  /**
462   * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
463   * exclusive. This is equivalent to {@code
464   * Collections.reverse(Doubles.asList(array).subList(fromIndex, toIndex))}, but is likely to be
465   * more efficient.
466   *
467   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
468   *     {@code toIndex > fromIndex}
469   * @since 23.1
470   */
471  public static void reverse(double[] array, int fromIndex, int toIndex) {
472    checkNotNull(array);
473    checkPositionIndexes(fromIndex, toIndex, array.length);
474    for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) {
475      double tmp = array[i];
476      array[i] = array[j];
477      array[j] = tmp;
478    }
479  }
480
481  /**
482   * Performs a right rotation of {@code array} of "distance" places, so that the first element is
483   * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
484   * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Bytes.asList(array),
485   * distance)}, but is considerably faster and avoids allocation and garbage collection.
486   *
487   * <p>The provided "distance" may be negative, which will rotate left.
488   *
489   * @since 32.0.0
490   */
491  public static void rotate(double[] array, int distance) {
492    rotate(array, distance, 0, array.length);
493  }
494
495  /**
496   * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
497   * toIndex} exclusive. This is equivalent to {@code
498   * Collections.rotate(Bytes.asList(array).subList(fromIndex, toIndex), distance)}, but is
499   * considerably faster and avoids allocations and garbage collection.
500   *
501   * <p>The provided "distance" may be negative, which will rotate left.
502   *
503   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
504   *     {@code toIndex > fromIndex}
505   * @since 32.0.0
506   */
507  public static void rotate(double[] array, int distance, int fromIndex, int toIndex) {
508    // See Ints.rotate for more details about possible algorithms here.
509    checkNotNull(array);
510    checkPositionIndexes(fromIndex, toIndex, array.length);
511    if (array.length <= 1) {
512      return;
513    }
514
515    int length = toIndex - fromIndex;
516    // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
517    // places left to rotate.
518    int m = -distance % length;
519    m = (m < 0) ? m + length : m;
520    // The current index of what will become the first element of the rotated section.
521    int newFirstIndex = m + fromIndex;
522    if (newFirstIndex == fromIndex) {
523      return;
524    }
525
526    reverse(array, fromIndex, newFirstIndex);
527    reverse(array, newFirstIndex, toIndex);
528    reverse(array, fromIndex, toIndex);
529  }
530
531  /**
532   * Returns an array containing each value of {@code collection}, converted to a {@code double}
533   * value in the manner of {@link Number#doubleValue}.
534   *
535   * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}.
536   * Calling this method is as thread-safe as calling that method.
537   *
538   * @param collection a collection of {@code Number} instances
539   * @return an array containing the same values as {@code collection}, in the same order, converted
540   *     to primitives
541   * @throws NullPointerException if {@code collection} or any of its elements is null
542   * @since 1.0 (parameter was {@code Collection<Double>} before 12.0)
543   */
544  public static double[] toArray(Collection<? extends Number> collection) {
545    if (collection instanceof DoubleArrayAsList) {
546      return ((DoubleArrayAsList) collection).toDoubleArray();
547    }
548
549    Object[] boxedArray = collection.toArray();
550    int len = boxedArray.length;
551    double[] array = new double[len];
552    for (int i = 0; i < len; i++) {
553      // checkNotNull for GWT (do not optimize)
554      array[i] = ((Number) checkNotNull(boxedArray[i])).doubleValue();
555    }
556    return array;
557  }
558
559  /**
560   * Returns a fixed-size list backed by the specified array, similar to {@link
561   * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to
562   * set a value to {@code null} will result in a {@link NullPointerException}.
563   *
564   * <p>The returned list maintains the values, but not the identities, of {@code Double} objects
565   * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
566   * the returned list is unspecified.
567   *
568   * <p>The returned list may have unexpected behavior if it contains {@code NaN}, or if {@code NaN}
569   * is used as a parameter to any of its methods.
570   *
571   * <p>The returned list is serializable.
572   *
573   * <p><b>Note:</b> when possible, you should represent your data as an {@link
574   * ImmutableDoubleArray} instead, which has an {@link ImmutableDoubleArray#asList asList} view.
575   *
576   * @param backingArray the array to back the list
577   * @return a list view of the array
578   */
579  public static List<Double> asList(double... backingArray) {
580    if (backingArray.length == 0) {
581      return Collections.emptyList();
582    }
583    return new DoubleArrayAsList(backingArray);
584  }
585
586  @GwtCompatible
587  private static class DoubleArrayAsList extends AbstractList<Double>
588      implements RandomAccess, Serializable {
589    final double[] array;
590    final int start;
591    final int end;
592
593    DoubleArrayAsList(double[] array) {
594      this(array, 0, array.length);
595    }
596
597    DoubleArrayAsList(double[] array, int start, int end) {
598      this.array = array;
599      this.start = start;
600      this.end = end;
601    }
602
603    @Override
604    public int size() {
605      return end - start;
606    }
607
608    @Override
609    public boolean isEmpty() {
610      return false;
611    }
612
613    @Override
614    public Double get(int index) {
615      checkElementIndex(index, size());
616      return array[start + index];
617    }
618
619    @Override
620    public Spliterator.OfDouble spliterator() {
621      return Spliterators.spliterator(array, start, end, 0);
622    }
623
624    @Override
625    public boolean contains(@CheckForNull Object target) {
626      // Overridden to prevent a ton of boxing
627      return (target instanceof Double)
628          && Doubles.indexOf(array, (Double) target, start, end) != -1;
629    }
630
631    @Override
632    public int indexOf(@CheckForNull Object target) {
633      // Overridden to prevent a ton of boxing
634      if (target instanceof Double) {
635        int i = Doubles.indexOf(array, (Double) target, start, end);
636        if (i >= 0) {
637          return i - start;
638        }
639      }
640      return -1;
641    }
642
643    @Override
644    public int lastIndexOf(@CheckForNull Object target) {
645      // Overridden to prevent a ton of boxing
646      if (target instanceof Double) {
647        int i = Doubles.lastIndexOf(array, (Double) target, start, end);
648        if (i >= 0) {
649          return i - start;
650        }
651      }
652      return -1;
653    }
654
655    @Override
656    public Double set(int index, Double element) {
657      checkElementIndex(index, size());
658      double oldValue = array[start + index];
659      // checkNotNull for GWT (do not optimize)
660      array[start + index] = checkNotNull(element);
661      return oldValue;
662    }
663
664    @Override
665    public List<Double> subList(int fromIndex, int toIndex) {
666      int size = size();
667      checkPositionIndexes(fromIndex, toIndex, size);
668      if (fromIndex == toIndex) {
669        return Collections.emptyList();
670      }
671      return new DoubleArrayAsList(array, start + fromIndex, start + toIndex);
672    }
673
674    @Override
675    public boolean equals(@CheckForNull Object object) {
676      if (object == this) {
677        return true;
678      }
679      if (object instanceof DoubleArrayAsList) {
680        DoubleArrayAsList that = (DoubleArrayAsList) object;
681        int size = size();
682        if (that.size() != size) {
683          return false;
684        }
685        for (int i = 0; i < size; i++) {
686          if (array[start + i] != that.array[that.start + i]) {
687            return false;
688          }
689        }
690        return true;
691      }
692      return super.equals(object);
693    }
694
695    @Override
696    public int hashCode() {
697      int result = 1;
698      for (int i = start; i < end; i++) {
699        result = 31 * result + Doubles.hashCode(array[i]);
700      }
701      return result;
702    }
703
704    @Override
705    public String toString() {
706      StringBuilder builder = new StringBuilder(size() * 12);
707      builder.append('[').append(array[start]);
708      for (int i = start + 1; i < end; i++) {
709        builder.append(", ").append(array[i]);
710      }
711      return builder.append(']').toString();
712    }
713
714    double[] toDoubleArray() {
715      return Arrays.copyOfRange(array, start, end);
716    }
717
718    private static final long serialVersionUID = 0;
719  }
720
721  /**
722   * This is adapted from the regex suggested by {@link Double#valueOf(String)} for prevalidating
723   * inputs. All valid inputs must pass this regex, but it's semantically fine if not all inputs
724   * that pass this regex are valid -- only a performance hit is incurred, not a semantics bug.
725   */
726  @GwtIncompatible // regular expressions
727  static final
728  java.util.regex.Pattern
729      FLOATING_POINT_PATTERN = fpPattern();
730
731  @GwtIncompatible // regular expressions
732  private static
733  java.util.regex.Pattern
734      fpPattern() {
735    /*
736     * We use # instead of * for possessive quantifiers. This lets us strip them out when building
737     * the regex for RE2 (which doesn't support them) but leave them in when building it for
738     * java.util.regex (where we want them in order to avoid catastrophic backtracking).
739     */
740    String decimal = "(?:\\d+#(?:\\.\\d*#)?|\\.\\d+#)";
741    String completeDec = decimal + "(?:[eE][+-]?\\d+#)?[fFdD]?";
742    String hex = "(?:[0-9a-fA-F]+#(?:\\.[0-9a-fA-F]*#)?|\\.[0-9a-fA-F]+#)";
743    String completeHex = "0[xX]" + hex + "[pP][+-]?\\d+#[fFdD]?";
744    String fpPattern = "[+-]?(?:NaN|Infinity|" + completeDec + "|" + completeHex + ")";
745    fpPattern =
746        fpPattern.replace(
747            "#",
748            "+"
749            );
750    return
751    java.util.regex.Pattern
752        .compile(fpPattern);
753  }
754
755  /**
756   * Parses the specified string as a double-precision floating point value. The ASCII character
757   * {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the minus sign.
758   *
759   * <p>Unlike {@link Double#parseDouble(String)}, this method returns {@code null} instead of
760   * throwing an exception if parsing fails. Valid inputs are exactly those accepted by {@link
761   * Double#valueOf(String)}, except that leading and trailing whitespace is not permitted.
762   *
763   * <p>This implementation is likely to be faster than {@code Double.parseDouble} if many failures
764   * are expected.
765   *
766   * @param string the string representation of a {@code double} value
767   * @return the floating point value represented by {@code string}, or {@code null} if {@code
768   *     string} has a length of zero or cannot be parsed as a {@code double} value
769   * @throws NullPointerException if {@code string} is {@code null}
770   * @since 14.0
771   */
772  @GwtIncompatible // regular expressions
773  @CheckForNull
774  public static Double tryParse(String string) {
775    if (FLOATING_POINT_PATTERN.matcher(string).matches()) {
776      // TODO(lowasser): could be potentially optimized, but only with
777      // extensive testing
778      try {
779        return Double.parseDouble(string);
780      } catch (NumberFormatException e) {
781        // Double.parseDouble has changed specs several times, so fall through
782        // gracefully
783      }
784    }
785    return null;
786  }
787}