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 values from each provided array combined into a single array. For example, 240 * {@code concat(new float[] {a, b}, new float[] {}, new float[] {c}} returns the array {@code {a, 241 * b, c}}. 242 * 243 * @param arrays zero or more {@code float} arrays 244 * @return a single array containing all the values from the source arrays, in order 245 */ 246 public static float[] concat(float[]... arrays) { 247 int length = 0; 248 for (float[] array : arrays) { 249 length += array.length; 250 } 251 float[] result = new float[length]; 252 int pos = 0; 253 for (float[] array : arrays) { 254 System.arraycopy(array, 0, result, pos, array.length); 255 pos += array.length; 256 } 257 return result; 258 } 259 260 private static final class FloatConverter extends Converter<String, Float> 261 implements Serializable { 262 static final FloatConverter INSTANCE = new FloatConverter(); 263 264 @Override 265 protected Float doForward(String value) { 266 return Float.valueOf(value); 267 } 268 269 @Override 270 protected String doBackward(Float value) { 271 return value.toString(); 272 } 273 274 @Override 275 public String toString() { 276 return "Floats.stringConverter()"; 277 } 278 279 private Object readResolve() { 280 return INSTANCE; 281 } 282 283 private static final long serialVersionUID = 1; 284 } 285 286 /** 287 * Returns a serializable converter object that converts between strings and floats using 288 * {@link Float#valueOf} and {@link Float#toString()}. 289 * 290 * @since 16.0 291 */ 292 @Beta 293 public static Converter<String, Float> stringConverter() { 294 return FloatConverter.INSTANCE; 295 } 296 297 /** 298 * Returns an array containing the same values as {@code array}, but guaranteed to be of a 299 * specified minimum length. If {@code array} already has a length of at least {@code minLength}, 300 * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is 301 * returned, containing the values of {@code array}, and zeroes in the remaining places. 302 * 303 * @param array the source array 304 * @param minLength the minimum length the returned array must guarantee 305 * @param padding an extra amount to "grow" the array by if growth is necessary 306 * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative 307 * @return an array containing the values of {@code array}, with guaranteed minimum length 308 * {@code minLength} 309 */ 310 public static float[] ensureCapacity(float[] array, int minLength, int padding) { 311 checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); 312 checkArgument(padding >= 0, "Invalid padding: %s", padding); 313 return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array; 314 } 315 316 /** 317 * Returns a string containing the supplied {@code float} values, converted to strings as 318 * specified by {@link Float#toString(float)}, and separated by {@code separator}. For example, 319 * {@code join("-", 1.0f, 2.0f, 3.0f)} returns the string {@code "1.0-2.0-3.0"}. 320 * 321 * <p>Note that {@link Float#toString(float)} formats {@code float} differently in GWT. In the 322 * previous example, it returns the string {@code 323 * "1-2-3"}. 324 * 325 * @param separator the text that should appear between consecutive values in the resulting string 326 * (but not at the start or end) 327 * @param array an array of {@code float} values, possibly empty 328 */ 329 public static String join(String separator, float... array) { 330 checkNotNull(separator); 331 if (array.length == 0) { 332 return ""; 333 } 334 335 // For pre-sizing a builder, just get the right order of magnitude 336 StringBuilder builder = new StringBuilder(array.length * 12); 337 builder.append(array[0]); 338 for (int i = 1; i < array.length; i++) { 339 builder.append(separator).append(array[i]); 340 } 341 return builder.toString(); 342 } 343 344 /** 345 * Returns a comparator that compares two {@code float} arrays <a 346 * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it 347 * compares, using {@link #compare(float, float)}), the first pair of values that follow any 348 * common prefix, or when one array is a prefix of the other, treats the shorter array as the 349 * lesser. For example, {@code [] < [1.0f] < [1.0f, 2.0f] < [2.0f]}. 350 * 351 * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays 352 * support only identity equality), but it is consistent with 353 * {@link Arrays#equals(float[], float[])}. 354 * 355 * @since 2.0 356 */ 357 public static Comparator<float[]> lexicographicalComparator() { 358 return LexicographicalComparator.INSTANCE; 359 } 360 361 private enum LexicographicalComparator implements Comparator<float[]> { 362 INSTANCE; 363 364 @Override 365 public int compare(float[] left, float[] right) { 366 int minLength = Math.min(left.length, right.length); 367 for (int i = 0; i < minLength; i++) { 368 int result = Float.compare(left[i], right[i]); 369 if (result != 0) { 370 return result; 371 } 372 } 373 return left.length - right.length; 374 } 375 376 @Override 377 public String toString() { 378 return "Floats.lexicographicalComparator()"; 379 } 380 } 381 382 /** 383 * Returns an array containing each value of {@code collection}, converted to a {@code float} 384 * value in the manner of {@link Number#floatValue}. 385 * 386 * <p>Elements are copied from the argument collection as if by {@code 387 * collection.toArray()}. Calling this method is as thread-safe as calling that method. 388 * 389 * @param collection a collection of {@code Number} instances 390 * @return an array containing the same values as {@code collection}, in the same order, converted 391 * to primitives 392 * @throws NullPointerException if {@code collection} or any of its elements is null 393 * @since 1.0 (parameter was {@code Collection<Float>} before 12.0) 394 */ 395 public static float[] toArray(Collection<? extends Number> collection) { 396 if (collection instanceof FloatArrayAsList) { 397 return ((FloatArrayAsList) collection).toFloatArray(); 398 } 399 400 Object[] boxedArray = collection.toArray(); 401 int len = boxedArray.length; 402 float[] array = new float[len]; 403 for (int i = 0; i < len; i++) { 404 // checkNotNull for GWT (do not optimize) 405 array[i] = ((Number) checkNotNull(boxedArray[i])).floatValue(); 406 } 407 return array; 408 } 409 410 /** 411 * Returns a fixed-size list backed by the specified array, similar to 412 * {@link Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any 413 * attempt to set a value to {@code null} will result in a {@link NullPointerException}. 414 * 415 * <p>The returned list maintains the values, but not the identities, of {@code Float} objects 416 * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for 417 * the returned list is unspecified. 418 * 419 * <p>The returned list may have unexpected behavior if it contains {@code 420 * NaN}, or if {@code NaN} is used as a parameter to any of its methods. 421 * 422 * @param backingArray the array to back the list 423 * @return a list view of the array 424 */ 425 public static List<Float> asList(float... backingArray) { 426 if (backingArray.length == 0) { 427 return Collections.emptyList(); 428 } 429 return new FloatArrayAsList(backingArray); 430 } 431 432 @GwtCompatible 433 private static class FloatArrayAsList extends AbstractList<Float> 434 implements RandomAccess, Serializable { 435 final float[] array; 436 final int start; 437 final int end; 438 439 FloatArrayAsList(float[] array) { 440 this(array, 0, array.length); 441 } 442 443 FloatArrayAsList(float[] array, int start, int end) { 444 this.array = array; 445 this.start = start; 446 this.end = end; 447 } 448 449 @Override 450 public int size() { 451 return end - start; 452 } 453 454 @Override 455 public boolean isEmpty() { 456 return false; 457 } 458 459 @Override 460 public Float get(int index) { 461 checkElementIndex(index, size()); 462 return array[start + index]; 463 } 464 465 @Override 466 public boolean contains(Object target) { 467 // Overridden to prevent a ton of boxing 468 return (target instanceof Float) && Floats.indexOf(array, (Float) target, start, end) != -1; 469 } 470 471 @Override 472 public int indexOf(Object target) { 473 // Overridden to prevent a ton of boxing 474 if (target instanceof Float) { 475 int i = Floats.indexOf(array, (Float) target, start, end); 476 if (i >= 0) { 477 return i - start; 478 } 479 } 480 return -1; 481 } 482 483 @Override 484 public int lastIndexOf(Object target) { 485 // Overridden to prevent a ton of boxing 486 if (target instanceof Float) { 487 int i = Floats.lastIndexOf(array, (Float) target, start, end); 488 if (i >= 0) { 489 return i - start; 490 } 491 } 492 return -1; 493 } 494 495 @Override 496 public Float set(int index, Float element) { 497 checkElementIndex(index, size()); 498 float oldValue = array[start + index]; 499 // checkNotNull for GWT (do not optimize) 500 array[start + index] = checkNotNull(element); 501 return oldValue; 502 } 503 504 @Override 505 public List<Float> subList(int fromIndex, int toIndex) { 506 int size = size(); 507 checkPositionIndexes(fromIndex, toIndex, size); 508 if (fromIndex == toIndex) { 509 return Collections.emptyList(); 510 } 511 return new FloatArrayAsList(array, start + fromIndex, start + toIndex); 512 } 513 514 @Override 515 public boolean equals(@Nullable Object object) { 516 if (object == this) { 517 return true; 518 } 519 if (object instanceof FloatArrayAsList) { 520 FloatArrayAsList that = (FloatArrayAsList) object; 521 int size = size(); 522 if (that.size() != size) { 523 return false; 524 } 525 for (int i = 0; i < size; i++) { 526 if (array[start + i] != that.array[that.start + i]) { 527 return false; 528 } 529 } 530 return true; 531 } 532 return super.equals(object); 533 } 534 535 @Override 536 public int hashCode() { 537 int result = 1; 538 for (int i = start; i < end; i++) { 539 result = 31 * result + Floats.hashCode(array[i]); 540 } 541 return result; 542 } 543 544 @Override 545 public String toString() { 546 StringBuilder builder = new StringBuilder(size() * 12); 547 builder.append('[').append(array[start]); 548 for (int i = start + 1; i < end; i++) { 549 builder.append(", ").append(array[i]); 550 } 551 return builder.append(']').toString(); 552 } 553 554 float[] toFloatArray() { 555 // Arrays.copyOfRange() is not available under GWT 556 int size = size(); 557 float[] result = new float[size]; 558 System.arraycopy(array, start, result, 0, size); 559 return result; 560 } 561 562 private static final long serialVersionUID = 0; 563 } 564 565 /** 566 * Parses the specified string as a single-precision floating point value. The ASCII character 567 * {@code '-'} (<code>'\u002D'</code>) is recognized as the minus sign. 568 * 569 * <p>Unlike {@link Float#parseFloat(String)}, this method returns {@code null} instead of 570 * throwing an exception if parsing fails. Valid inputs are exactly those accepted by 571 * {@link Float#valueOf(String)}, except that leading and trailing whitespace is not permitted. 572 * 573 * <p>This implementation is likely to be faster than {@code 574 * Float.parseFloat} if many failures are expected. 575 * 576 * @param string the string representation of a {@code float} value 577 * @return the floating point value represented by {@code string}, or {@code null} if 578 * {@code string} has a length of zero or cannot be parsed as a {@code float} value 579 * @since 14.0 580 */ 581 @Beta 582 @Nullable 583 @CheckForNull 584 @GwtIncompatible // regular expressions 585 public static Float tryParse(String string) { 586 if (Doubles.FLOATING_POINT_PATTERN.matcher(string).matches()) { 587 // TODO(lowasser): could be potentially optimized, but only with 588 // extensive testing 589 try { 590 return Float.parseFloat(string); 591 } catch (NumberFormatException e) { 592 // Float.parseFloat has changed specs several times, so fall through 593 // gracefully 594 } 595 } 596 return null; 597 } 598}