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