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