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