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