001/*
002 * Copyright (C) 2008 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.primitives;
018
019import static com.google.common.base.Preconditions.checkArgument;
020import static com.google.common.base.Preconditions.checkElementIndex;
021import static com.google.common.base.Preconditions.checkNotNull;
022import static com.google.common.base.Preconditions.checkPositionIndexes;
023import static java.lang.Float.NEGATIVE_INFINITY;
024import static java.lang.Float.POSITIVE_INFINITY;
025
026import com.google.common.annotations.Beta;
027import com.google.common.annotations.GwtCompatible;
028import com.google.common.annotations.GwtIncompatible;
029import com.google.common.base.Converter;
030
031import java.io.Serializable;
032import java.util.AbstractList;
033import java.util.Arrays;
034import java.util.Collection;
035import java.util.Collections;
036import java.util.Comparator;
037import java.util.List;
038import java.util.RandomAccess;
039
040import javax.annotation.Nullable;
041
042/**
043 * Static utility methods pertaining to {@code float} primitives, that are not
044 * already found in either {@link Float} or {@link Arrays}.
045 *
046 * <p>See the Guava User Guide article on <a href=
047 * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
048 * primitive utilities</a>.
049 *
050 * @author Kevin Bourrillion
051 * @since 1.0
052 */
053@GwtCompatible(emulated = true)
054public final class Floats {
055  private Floats() {}
056
057  /**
058   * The number of bytes required to represent a primitive {@code float}
059   * value.
060   *
061   * @since 10.0
062   */
063  public static final int BYTES = Float.SIZE / Byte.SIZE;
064
065  /**
066   * Returns a hash code for {@code value}; equal to the result of invoking
067   * {@code ((Float) value).hashCode()}.
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
079   * Float#compare(float, float)}. You may prefer to invoke that method
080   * directly; this method exists only for consistency with the other utilities
081   * in this package.
082   *
083   * <p><b>Note:</b> this method simply delegates to the JDK method {@link
084   * Float#compare}. It is provided for consistency with the other primitive
085   * types, whose compare methods were not added to the JDK until JDK 7.
086   *
087   * @param a the first {@code float} to compare
088   * @param b the second {@code float} to compare
089   * @return the result of invoking {@link Float#compare(float, float)}
090   */
091  // TODO(kevinb): if Ints.compare etc. are ever removed, remove this one too
092  public static int compare(float a, float b) {
093    return Float.compare(a, b);
094  }
095
096  /**
097   * Returns {@code true} if {@code value} represents a real number. This is
098   * equivalent to, but not necessarily implemented as,
099   * {@code !(Float.isInfinite(value) || Float.isNaN(value))}.
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
109   * {@code array}. Note that this always returns {@code false} when {@code
110   * target} is {@code NaN}.
111   *
112   * @param array an array of {@code float} values, possibly empty
113   * @param target a primitive {@code float} value
114   * @return {@code true} if {@code array[i] == target} for some value of {@code
115   *     i}
116   */
117  public static boolean contains(float[] array, float target) {
118    for (float value : array) {
119      if (value == target) {
120        return true;
121      }
122    }
123    return false;
124  }
125
126  /**
127   * Returns the index of the first appearance of the value {@code target} in
128   * {@code array}. Note that this always returns {@code -1} when {@code target}
129   * is {@code NaN}.
130   *
131   * @param array an array of {@code float} values, possibly empty
132   * @param target a primitive {@code float} value
133   * @return the least index {@code i} for which {@code array[i] == target}, or
134   *     {@code -1} if no such index exists.
135   */
136  public static int indexOf(float[] array, float target) {
137    return indexOf(array, target, 0, array.length);
138  }
139
140  // TODO(kevinb): consider making this public
141  private static int indexOf(
142      float[] array, float 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
153   * target} within {@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
156   * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
157   * the same elements as {@code target}.
158   *
159   * <p>Note that this always returns {@code -1} when {@code target} contains
160   * {@code NaN}.
161   *
162   * @param array the array to search for the sequence {@code target}
163   * @param target the array to search for as a sub-sequence of {@code array}
164   */
165  public static int indexOf(float[] array, float[] target) {
166    checkNotNull(array, "array");
167    checkNotNull(target, "target");
168    if (target.length == 0) {
169      return 0;
170    }
171
172    outer:
173    for (int i = 0; i < array.length - target.length + 1; i++) {
174      for (int j = 0; j < target.length; j++) {
175        if (array[i + j] != target[j]) {
176          continue outer;
177        }
178      }
179      return i;
180    }
181    return -1;
182  }
183
184  /**
185   * Returns the index of the last appearance of the value {@code target} in
186   * {@code array}. Note that this always returns {@code -1} when {@code target}
187   * is {@code NaN}.
188   *
189   * @param array an array of {@code float} values, possibly empty
190   * @param target a primitive {@code float} value
191   * @return the greatest index {@code i} for which {@code array[i] == target},
192   *     or {@code -1} if no such index exists.
193   */
194  public static int lastIndexOf(float[] array, float target) {
195    return lastIndexOf(array, target, 0, array.length);
196  }
197
198  // TODO(kevinb): consider making this public
199  private static int lastIndexOf(
200      float[] array, float target, int start, int end) {
201    for (int i = end - 1; i >= start; i--) {
202      if (array[i] == target) {
203        return i;
204      }
205    }
206    return -1;
207  }
208
209  /**
210   * Returns the least value present in {@code array}, using the same rules of
211   * comparison as {@link Math#min(float, float)}.
212   *
213   * @param array a <i>nonempty</i> array of {@code float} values
214   * @return the value present in {@code array} that is less than or equal to
215   *     every other value in the array
216   * @throws IllegalArgumentException if {@code array} is empty
217   */
218  public static float min(float... array) {
219    checkArgument(array.length > 0);
220    float min = array[0];
221    for (int i = 1; i < array.length; i++) {
222      min = Math.min(min, array[i]);
223    }
224    return min;
225  }
226
227  /**
228   * Returns the greatest value present in {@code array}, using the same rules
229   * of comparison as {@link Math#min(float, float)}.
230   *
231   * @param array a <i>nonempty</i> array of {@code float} values
232   * @return the value present in {@code array} that is greater than or equal to
233   *     every other value in the array
234   * @throws IllegalArgumentException if {@code array} is empty
235   */
236  public static float max(float... array) {
237    checkArgument(array.length > 0);
238    float 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 values from each provided array combined into a single array.
247   * For example, {@code concat(new float[] {a, b}, new float[] {}, new
248   * float[] {c}} returns the array {@code {a, b, c}}.
249   *
250   * @param arrays zero or more {@code float} arrays
251   * @return a single array containing all the values from the source arrays, in
252   *     order
253   */
254  public static float[] concat(float[]... arrays) {
255    int length = 0;
256    for (float[] array : arrays) {
257      length += array.length;
258    }
259    float[] result = new float[length];
260    int pos = 0;
261    for (float[] array : arrays) {
262      System.arraycopy(array, 0, result, pos, array.length);
263      pos += array.length;
264    }
265    return result;
266  }
267
268  private static final class FloatConverter
269      extends Converter<String, Float> implements Serializable {
270    static final FloatConverter INSTANCE = new FloatConverter();
271
272    @Override
273    protected Float doForward(String value) {
274      // TODO(kevinb): remove null boilerplate (convert() will do it
275      // automatically)
276      return value == null ? null : Float.valueOf(value);
277    }
278
279    @Override
280    protected String doBackward(Float value) {
281      // TODO(kevinb): remove null boilerplate (convert() will do it
282      // automatically)
283      return value == null ? null : value.toString();
284    }
285
286    @Override
287    public String toString() {
288      return "Floats.stringConverter()";
289    }
290
291    private Object readResolve() {
292      return INSTANCE;
293    }
294    private static final long serialVersionUID = 1;
295  }
296
297  /**
298   * Returns a serializable converter object that converts between strings and
299   * floats using {@link Float#valueOf} and {@link Float#toString()}.
300   *
301   * @since 16.0
302   */
303  @Beta
304  public static Converter<String, Float> stringConverter() {
305    return FloatConverter.INSTANCE;
306  }
307
308  /**
309   * Returns an array containing the same values as {@code array}, but
310   * guaranteed to be of a specified minimum length. If {@code array} already
311   * has a length of at least {@code minLength}, it is returned directly.
312   * Otherwise, a new array of size {@code minLength + padding} is returned,
313   * containing the values of {@code array}, and zeroes in the remaining places.
314   *
315   * @param array the source array
316   * @param minLength the minimum length the returned array must guarantee
317   * @param padding an extra amount to "grow" the array by if growth is
318   *     necessary
319   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is
320   *     negative
321   * @return an array containing the values of {@code array}, with guaranteed
322   *     minimum length {@code minLength}
323   */
324  public static float[] ensureCapacity(
325      float[] array, int minLength, int padding) {
326    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
327    checkArgument(padding >= 0, "Invalid padding: %s", padding);
328    return (array.length < minLength)
329        ? copyOf(array, minLength + padding)
330        : array;
331  }
332
333  // Arrays.copyOf() requires Java 6
334  private static float[] copyOf(float[] original, int length) {
335    float[] copy = new float[length];
336    System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
337    return copy;
338  }
339
340  /**
341   * Returns a string containing the supplied {@code float} values, converted
342   * to strings as specified by {@link Float#toString(float)}, and separated by
343   * {@code separator}. For example, {@code join("-", 1.0f, 2.0f, 3.0f)}
344   * returns the string {@code "1.0-2.0-3.0"}.
345   *
346   * <p>Note that {@link Float#toString(float)} formats {@code float}
347   * differently in GWT.  In the previous example, it returns the string {@code
348   * "1-2-3"}.
349   *
350   * @param separator the text that should appear between consecutive values in
351   *     the resulting string (but not at the start or end)
352   * @param array an array of {@code float} values, possibly empty
353   */
354  public static String join(String separator, float... array) {
355    checkNotNull(separator);
356    if (array.length == 0) {
357      return "";
358    }
359
360    // For pre-sizing a builder, just get the right order of magnitude
361    StringBuilder builder = new StringBuilder(array.length * 12);
362    builder.append(array[0]);
363    for (int i = 1; i < array.length; i++) {
364      builder.append(separator).append(array[i]);
365    }
366    return builder.toString();
367  }
368
369  /**
370   * Returns a comparator that compares two {@code float} arrays
371   * lexicographically. That is, it compares, using {@link
372   * #compare(float, float)}), the first pair of values that follow any
373   * common prefix, or when one array is a prefix of the other, treats the
374   * shorter array as the lesser. For example, {@code [] < [1.0f] < [1.0f, 2.0f]
375   * < [2.0f]}.
376   *
377   * <p>The returned comparator is inconsistent with {@link
378   * Object#equals(Object)} (since arrays support only identity equality), but
379   * it is consistent with {@link Arrays#equals(float[], float[])}.
380   *
381   * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
382   *     Lexicographical order article at Wikipedia</a>
383   * @since 2.0
384   */
385  public static Comparator<float[]> lexicographicalComparator() {
386    return LexicographicalComparator.INSTANCE;
387  }
388
389  private enum LexicographicalComparator implements Comparator<float[]> {
390    INSTANCE;
391
392    @Override
393    public int compare(float[] left, float[] right) {
394      int minLength = Math.min(left.length, right.length);
395      for (int i = 0; i < minLength; i++) {
396        int result = Floats.compare(left[i], right[i]);
397        if (result != 0) {
398          return result;
399        }
400      }
401      return left.length - right.length;
402    }
403  }
404
405  /**
406   * Returns an array containing each value of {@code collection}, converted to
407   * a {@code float} value in the manner of {@link Number#floatValue}.
408   *
409   * <p>Elements are copied from the argument collection as if by {@code
410   * collection.toArray()}.  Calling this method is as thread-safe as calling
411   * that method.
412   *
413   * @param collection a collection of {@code Number} instances
414   * @return an array containing the same values as {@code collection}, in the
415   *     same order, converted to primitives
416   * @throws NullPointerException if {@code collection} or any of its elements
417   *     is null
418   * @since 1.0 (parameter was {@code Collection<Float>} before 12.0)
419   */
420  public static float[] toArray(Collection<? extends Number> collection) {
421    if (collection instanceof FloatArrayAsList) {
422      return ((FloatArrayAsList) collection).toFloatArray();
423    }
424
425    Object[] boxedArray = collection.toArray();
426    int len = boxedArray.length;
427    float[] array = new float[len];
428    for (int i = 0; i < len; i++) {
429      // checkNotNull for GWT (do not optimize)
430      array[i] = ((Number) checkNotNull(boxedArray[i])).floatValue();
431    }
432    return array;
433  }
434
435  /**
436   * Returns a fixed-size list backed by the specified array, similar to {@link
437   * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
438   * but any attempt to set a value to {@code null} will result in a {@link
439   * NullPointerException}.
440   *
441   * <p>The returned list maintains the values, but not the identities, of
442   * {@code Float} objects written to or read from it.  For example, whether
443   * {@code list.get(0) == list.get(0)} is true for the returned list is
444   * unspecified.
445   *
446   * <p>The returned list may have unexpected behavior if it contains {@code
447   * NaN}, or if {@code NaN} is used as a parameter to any of its methods.
448   *
449   * @param backingArray the array to back the list
450   * @return a list view of the array
451   */
452  public static List<Float> asList(float... backingArray) {
453    if (backingArray.length == 0) {
454      return Collections.emptyList();
455    }
456    return new FloatArrayAsList(backingArray);
457  }
458
459  @GwtCompatible
460  private static class FloatArrayAsList extends AbstractList<Float>
461      implements RandomAccess, Serializable {
462    final float[] array;
463    final int start;
464    final int end;
465
466    FloatArrayAsList(float[] array) {
467      this(array, 0, array.length);
468    }
469
470    FloatArrayAsList(float[] array, int start, int end) {
471      this.array = array;
472      this.start = start;
473      this.end = end;
474    }
475
476    @Override public int size() {
477      return end - start;
478    }
479
480    @Override public boolean isEmpty() {
481      return false;
482    }
483
484    @Override public Float get(int index) {
485      checkElementIndex(index, size());
486      return array[start + index];
487    }
488
489    @Override public boolean contains(Object target) {
490      // Overridden to prevent a ton of boxing
491      return (target instanceof Float)
492          && Floats.indexOf(array, (Float) target, start, end) != -1;
493    }
494
495    @Override public int indexOf(Object target) {
496      // Overridden to prevent a ton of boxing
497      if (target instanceof Float) {
498        int i = Floats.indexOf(array, (Float) target, start, end);
499        if (i >= 0) {
500          return i - start;
501        }
502      }
503      return -1;
504    }
505
506    @Override public int lastIndexOf(Object target) {
507      // Overridden to prevent a ton of boxing
508      if (target instanceof Float) {
509        int i = Floats.lastIndexOf(array, (Float) target, start, end);
510        if (i >= 0) {
511          return i - start;
512        }
513      }
514      return -1;
515    }
516
517    @Override public Float set(int index, Float element) {
518      checkElementIndex(index, size());
519      float oldValue = array[start + index];
520      // checkNotNull for GWT (do not optimize)
521      array[start + index] = checkNotNull(element);
522      return oldValue;
523    }
524
525    @Override public List<Float> subList(int fromIndex, int toIndex) {
526      int size = size();
527      checkPositionIndexes(fromIndex, toIndex, size);
528      if (fromIndex == toIndex) {
529        return Collections.emptyList();
530      }
531      return new FloatArrayAsList(array, start + fromIndex, start + toIndex);
532    }
533
534    @Override public boolean equals(Object object) {
535      if (object == this) {
536        return true;
537      }
538      if (object instanceof FloatArrayAsList) {
539        FloatArrayAsList that = (FloatArrayAsList) object;
540        int size = size();
541        if (that.size() != size) {
542          return false;
543        }
544        for (int i = 0; i < size; i++) {
545          if (array[start + i] != that.array[that.start + i]) {
546            return false;
547          }
548        }
549        return true;
550      }
551      return super.equals(object);
552    }
553
554    @Override public int hashCode() {
555      int result = 1;
556      for (int i = start; i < end; i++) {
557        result = 31 * result + Floats.hashCode(array[i]);
558      }
559      return result;
560    }
561
562    @Override public String toString() {
563      StringBuilder builder = new StringBuilder(size() * 12);
564      builder.append('[').append(array[start]);
565      for (int i = start + 1; i < end; i++) {
566        builder.append(", ").append(array[i]);
567      }
568      return builder.append(']').toString();
569    }
570
571    float[] toFloatArray() {
572      // Arrays.copyOfRange() is not available under GWT
573      int size = size();
574      float[] result = new float[size];
575      System.arraycopy(array, start, result, 0, size);
576      return result;
577    }
578
579    private static final long serialVersionUID = 0;
580  }
581
582  /**
583   * Parses the specified string as a single-precision floating point value.
584   * The ASCII character {@code '-'} (<code>'&#92;u002D'</code>) is recognized
585   * as the minus sign.
586   *
587   * <p>Unlike {@link Float#parseFloat(String)}, this method returns
588   * {@code null} instead of throwing an exception if parsing fails.
589   * Valid inputs are exactly those accepted by {@link Float#valueOf(String)},
590   * except that leading and trailing whitespace is not permitted.
591   *
592   * <p>This implementation is likely to be faster than {@code
593   * Float.parseFloat} if many failures are expected.
594   *
595   * @param string the string representation of a {@code float} value
596   * @return the floating point value represented by {@code string}, or
597   *     {@code null} if {@code string} has a length of zero or cannot be
598   *     parsed as a {@code float} value
599   * @since 14.0
600   */
601  @GwtIncompatible("regular expressions")
602  @Nullable
603  @Beta
604  public static Float tryParse(String string) {
605    if (Doubles.FLOATING_POINT_PATTERN.matcher(string).matches()) {
606      // TODO(user): could be potentially optimized, but only with
607      // extensive testing
608      try {
609        return Float.parseFloat(string);
610      } catch (NumberFormatException e) {
611        // Float.parseFloat has changed specs several times, so fall through
612        // gracefully
613      }
614    }
615    return null;
616  }
617}