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.CheckForNull; 041import javax.annotation.CheckReturnValue; 042import javax.annotation.Nullable; 043 044/** 045 * Static utility methods pertaining to {@code float} primitives, that are not 046 * already found in either {@link Float} or {@link Arrays}. 047 * 048 * <p>See the Guava User Guide article on <a href= 049 * "https://github.com/google/guava/wiki/PrimitivesExplained"> 050 * primitive utilities</a>. 051 * 052 * @author Kevin Bourrillion 053 * @since 1.0 054 */ 055@CheckReturnValue 056@GwtCompatible(emulated = true) 057public final class Floats { 058 private Floats() {} 059 060 /** 061 * The number of bytes required to represent a primitive {@code float} 062 * value. 063 * 064 * @since 10.0 065 */ 066 public static final int BYTES = Float.SIZE / Byte.SIZE; 067 068 /** 069 * Returns a hash code for {@code value}; equal to the result of invoking 070 * {@code ((Float) value).hashCode()}. 071 * 072 * @param value a primitive {@code float} value 073 * @return a hash code for the value 074 */ 075 public static int hashCode(float value) { 076 // TODO(kevinb): is there a better way, that's still gwt-safe? 077 return ((Float) value).hashCode(); 078 } 079 080 /** 081 * Compares the two specified {@code float} values using {@link 082 * Float#compare(float, float)}. You may prefer to invoke that method 083 * directly; this method exists only for consistency with the other utilities 084 * in this package. 085 * 086 * <p><b>Note:</b> this method simply delegates to the JDK method {@link 087 * Float#compare}. It is provided for consistency with the other primitive 088 * types, whose compare methods were not added to the JDK until JDK 7. 089 * 090 * @param a the first {@code float} to compare 091 * @param b the second {@code float} to compare 092 * @return the result of invoking {@link Float#compare(float, float)} 093 */ 094 public static int compare(float a, float b) { 095 return Float.compare(a, b); 096 } 097 098 /** 099 * Returns {@code true} if {@code value} represents a real number. This is 100 * equivalent to, but not necessarily implemented as, 101 * {@code !(Float.isInfinite(value) || Float.isNaN(value))}. 102 * 103 * @since 10.0 104 */ 105 public static boolean isFinite(float value) { 106 return NEGATIVE_INFINITY < value & value < POSITIVE_INFINITY; 107 } 108 109 /** 110 * Returns {@code true} if {@code target} is present as an element anywhere in 111 * {@code array}. Note that this always returns {@code false} when {@code 112 * target} is {@code NaN}. 113 * 114 * @param array an array of {@code float} values, possibly empty 115 * @param target a primitive {@code float} value 116 * @return {@code true} if {@code array[i] == target} for some value of {@code 117 * i} 118 */ 119 public static boolean contains(float[] array, float target) { 120 for (float value : array) { 121 if (value == target) { 122 return true; 123 } 124 } 125 return false; 126 } 127 128 /** 129 * Returns the index of the first appearance of the value {@code target} in 130 * {@code array}. Note that this always returns {@code -1} when {@code target} 131 * is {@code NaN}. 132 * 133 * @param array an array of {@code float} values, possibly empty 134 * @param target a primitive {@code float} value 135 * @return the least index {@code i} for which {@code array[i] == target}, or 136 * {@code -1} if no such index exists. 137 */ 138 public static int indexOf(float[] array, float target) { 139 return indexOf(array, target, 0, array.length); 140 } 141 142 // TODO(kevinb): consider making this public 143 private static int indexOf(float[] array, float target, int start, int end) { 144 for (int i = start; i < end; i++) { 145 if (array[i] == target) { 146 return i; 147 } 148 } 149 return -1; 150 } 151 152 /** 153 * Returns the start position of the first occurrence of the specified {@code 154 * target} within {@code array}, or {@code -1} if there is no such occurrence. 155 * 156 * <p>More formally, returns the lowest index {@code i} such that {@code 157 * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly 158 * the same elements as {@code target}. 159 * 160 * <p>Note that this always returns {@code -1} when {@code target} contains 161 * {@code NaN}. 162 * 163 * @param array the array to search for the sequence {@code target} 164 * @param target the array to search for as a sub-sequence of {@code array} 165 */ 166 public static int indexOf(float[] array, float[] target) { 167 checkNotNull(array, "array"); 168 checkNotNull(target, "target"); 169 if (target.length == 0) { 170 return 0; 171 } 172 173 outer: 174 for (int i = 0; i < array.length - target.length + 1; i++) { 175 for (int j = 0; j < target.length; j++) { 176 if (array[i + j] != target[j]) { 177 continue outer; 178 } 179 } 180 return i; 181 } 182 return -1; 183 } 184 185 /** 186 * Returns the index of the last appearance of the value {@code target} in 187 * {@code array}. Note that this always returns {@code -1} when {@code target} 188 * is {@code NaN}. 189 * 190 * @param array an array of {@code float} values, possibly empty 191 * @param target a primitive {@code float} value 192 * @return the greatest index {@code i} for which {@code array[i] == target}, 193 * or {@code -1} if no such index exists. 194 */ 195 public static int lastIndexOf(float[] array, float target) { 196 return lastIndexOf(array, target, 0, array.length); 197 } 198 199 // TODO(kevinb): consider making this public 200 private static int lastIndexOf(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#max(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 extends Converter<String, Float> 269 implements Serializable { 270 static final FloatConverter INSTANCE = new FloatConverter(); 271 272 @Override 273 protected Float doForward(String value) { 274 return Float.valueOf(value); 275 } 276 277 @Override 278 protected String doBackward(Float value) { 279 return value.toString(); 280 } 281 282 @Override 283 public String toString() { 284 return "Floats.stringConverter()"; 285 } 286 287 private Object readResolve() { 288 return INSTANCE; 289 } 290 291 private static final long serialVersionUID = 1; 292 } 293 294 /** 295 * Returns a serializable converter object that converts between strings and 296 * floats using {@link Float#valueOf} and {@link Float#toString()}. 297 * 298 * @since 16.0 299 */ 300 @Beta 301 public static Converter<String, Float> stringConverter() { 302 return FloatConverter.INSTANCE; 303 } 304 305 /** 306 * Returns an array containing the same values as {@code array}, but 307 * guaranteed to be of a specified minimum length. If {@code array} already 308 * has a length of at least {@code minLength}, it is returned directly. 309 * Otherwise, a new array of size {@code minLength + padding} is returned, 310 * containing the values of {@code array}, and zeroes in the remaining places. 311 * 312 * @param array the source array 313 * @param minLength the minimum length the returned array must guarantee 314 * @param padding an extra amount to "grow" the array by if growth is 315 * necessary 316 * @throws IllegalArgumentException if {@code minLength} or {@code padding} is 317 * negative 318 * @return an array containing the values of {@code array}, with guaranteed 319 * minimum length {@code minLength} 320 */ 321 public static float[] ensureCapacity(float[] array, int minLength, int padding) { 322 checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); 323 checkArgument(padding >= 0, "Invalid padding: %s", padding); 324 return (array.length < minLength) 325 ? copyOf(array, minLength + padding) 326 : array; 327 } 328 329 // Arrays.copyOf() requires Java 6 330 private static float[] copyOf(float[] original, int length) { 331 float[] copy = new float[length]; 332 System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); 333 return copy; 334 } 335 336 /** 337 * Returns a string containing the supplied {@code float} values, converted 338 * to strings as specified by {@link Float#toString(float)}, and separated by 339 * {@code separator}. For example, {@code join("-", 1.0f, 2.0f, 3.0f)} 340 * returns the string {@code "1.0-2.0-3.0"}. 341 * 342 * <p>Note that {@link Float#toString(float)} formats {@code float} 343 * differently in GWT. In the previous example, it returns the string {@code 344 * "1-2-3"}. 345 * 346 * @param separator the text that should appear between consecutive values in 347 * the resulting string (but not at the start or end) 348 * @param array an array of {@code float} values, possibly empty 349 */ 350 public static String join(String separator, float... array) { 351 checkNotNull(separator); 352 if (array.length == 0) { 353 return ""; 354 } 355 356 // For pre-sizing a builder, just get the right order of magnitude 357 StringBuilder builder = new StringBuilder(array.length * 12); 358 builder.append(array[0]); 359 for (int i = 1; i < array.length; i++) { 360 builder.append(separator).append(array[i]); 361 } 362 return builder.toString(); 363 } 364 365 /** 366 * Returns a comparator that compares two {@code float} arrays 367 * lexicographically. That is, it compares, using {@link 368 * #compare(float, float)}), the first pair of values that follow any 369 * common prefix, or when one array is a prefix of the other, treats the 370 * shorter array as the lesser. For example, {@code [] < [1.0f] < [1.0f, 2.0f] 371 * < [2.0f]}. 372 * 373 * <p>The returned comparator is inconsistent with {@link 374 * Object#equals(Object)} (since arrays support only identity equality), but 375 * it is consistent with {@link Arrays#equals(float[], float[])}. 376 * 377 * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> 378 * Lexicographical order article at Wikipedia</a> 379 * @since 2.0 380 */ 381 public static Comparator<float[]> lexicographicalComparator() { 382 return LexicographicalComparator.INSTANCE; 383 } 384 385 private enum LexicographicalComparator implements Comparator<float[]> { 386 INSTANCE; 387 388 @Override 389 public int compare(float[] left, float[] right) { 390 int minLength = Math.min(left.length, right.length); 391 for (int i = 0; i < minLength; i++) { 392 int result = Float.compare(left[i], right[i]); 393 if (result != 0) { 394 return result; 395 } 396 } 397 return left.length - right.length; 398 } 399 } 400 401 /** 402 * Returns an array containing each value of {@code collection}, converted to 403 * a {@code float} value in the manner of {@link Number#floatValue}. 404 * 405 * <p>Elements are copied from the argument collection as if by {@code 406 * collection.toArray()}. Calling this method is as thread-safe as calling 407 * that method. 408 * 409 * @param collection a collection of {@code Number} instances 410 * @return an array containing the same values as {@code collection}, in the 411 * same order, converted to primitives 412 * @throws NullPointerException if {@code collection} or any of its elements 413 * is null 414 * @since 1.0 (parameter was {@code Collection<Float>} before 12.0) 415 */ 416 public static float[] toArray(Collection<? extends Number> collection) { 417 if (collection instanceof FloatArrayAsList) { 418 return ((FloatArrayAsList) collection).toFloatArray(); 419 } 420 421 Object[] boxedArray = collection.toArray(); 422 int len = boxedArray.length; 423 float[] array = new float[len]; 424 for (int i = 0; i < len; i++) { 425 // checkNotNull for GWT (do not optimize) 426 array[i] = ((Number) checkNotNull(boxedArray[i])).floatValue(); 427 } 428 return array; 429 } 430 431 /** 432 * Returns a fixed-size list backed by the specified array, similar to {@link 433 * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, 434 * but any attempt to set a value to {@code null} will result in a {@link 435 * NullPointerException}. 436 * 437 * <p>The returned list maintains the values, but not the identities, of 438 * {@code Float} objects written to or read from it. For example, whether 439 * {@code list.get(0) == list.get(0)} is true for the returned list is 440 * unspecified. 441 * 442 * <p>The returned list may have unexpected behavior if it contains {@code 443 * NaN}, or if {@code NaN} is used as a parameter to any of its methods. 444 * 445 * @param backingArray the array to back the list 446 * @return a list view of the array 447 */ 448 public static List<Float> asList(float... backingArray) { 449 if (backingArray.length == 0) { 450 return Collections.emptyList(); 451 } 452 return new FloatArrayAsList(backingArray); 453 } 454 455 @GwtCompatible 456 private static class FloatArrayAsList extends AbstractList<Float> 457 implements RandomAccess, Serializable { 458 final float[] array; 459 final int start; 460 final int end; 461 462 FloatArrayAsList(float[] array) { 463 this(array, 0, array.length); 464 } 465 466 FloatArrayAsList(float[] array, int start, int end) { 467 this.array = array; 468 this.start = start; 469 this.end = end; 470 } 471 472 @Override 473 public int size() { 474 return end - start; 475 } 476 477 @Override 478 public boolean isEmpty() { 479 return false; 480 } 481 482 @Override 483 public Float get(int index) { 484 checkElementIndex(index, size()); 485 return array[start + index]; 486 } 487 488 @Override 489 public boolean contains(Object target) { 490 // Overridden to prevent a ton of boxing 491 return (target instanceof Float) && Floats.indexOf(array, (Float) target, start, end) != -1; 492 } 493 494 @Override 495 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 507 public int lastIndexOf(Object target) { 508 // Overridden to prevent a ton of boxing 509 if (target instanceof Float) { 510 int i = Floats.lastIndexOf(array, (Float) target, start, end); 511 if (i >= 0) { 512 return i - start; 513 } 514 } 515 return -1; 516 } 517 518 @Override 519 public Float set(int index, Float element) { 520 checkElementIndex(index, size()); 521 float oldValue = array[start + index]; 522 // checkNotNull for GWT (do not optimize) 523 array[start + index] = checkNotNull(element); 524 return oldValue; 525 } 526 527 @Override 528 public List<Float> subList(int fromIndex, int toIndex) { 529 int size = size(); 530 checkPositionIndexes(fromIndex, toIndex, size); 531 if (fromIndex == toIndex) { 532 return Collections.emptyList(); 533 } 534 return new FloatArrayAsList(array, start + fromIndex, start + toIndex); 535 } 536 537 @Override 538 public boolean equals(@Nullable Object object) { 539 if (object == this) { 540 return true; 541 } 542 if (object instanceof FloatArrayAsList) { 543 FloatArrayAsList that = (FloatArrayAsList) object; 544 int size = size(); 545 if (that.size() != size) { 546 return false; 547 } 548 for (int i = 0; i < size; i++) { 549 if (array[start + i] != that.array[that.start + i]) { 550 return false; 551 } 552 } 553 return true; 554 } 555 return super.equals(object); 556 } 557 558 @Override 559 public int hashCode() { 560 int result = 1; 561 for (int i = start; i < end; i++) { 562 result = 31 * result + Floats.hashCode(array[i]); 563 } 564 return result; 565 } 566 567 @Override 568 public String toString() { 569 StringBuilder builder = new StringBuilder(size() * 12); 570 builder.append('[').append(array[start]); 571 for (int i = start + 1; i < end; i++) { 572 builder.append(", ").append(array[i]); 573 } 574 return builder.append(']').toString(); 575 } 576 577 float[] toFloatArray() { 578 // Arrays.copyOfRange() is not available under GWT 579 int size = size(); 580 float[] result = new float[size]; 581 System.arraycopy(array, start, result, 0, size); 582 return result; 583 } 584 585 private static final long serialVersionUID = 0; 586 } 587 588 /** 589 * Parses the specified string as a single-precision floating point value. 590 * The ASCII character {@code '-'} (<code>'\u002D'</code>) is recognized 591 * as the minus sign. 592 * 593 * <p>Unlike {@link Float#parseFloat(String)}, this method returns 594 * {@code null} instead of throwing an exception if parsing fails. 595 * Valid inputs are exactly those accepted by {@link Float#valueOf(String)}, 596 * except that leading and trailing whitespace is not permitted. 597 * 598 * <p>This implementation is likely to be faster than {@code 599 * Float.parseFloat} if many failures are expected. 600 * 601 * @param string the string representation of a {@code float} value 602 * @return the floating point value represented by {@code string}, or 603 * {@code null} if {@code string} has a length of zero or cannot be 604 * parsed as a {@code float} value 605 * @since 14.0 606 */ 607 @Beta 608 @Nullable 609 @CheckForNull 610 @GwtIncompatible("regular expressions") 611 public static Float tryParse(String string) { 612 if (Doubles.FLOATING_POINT_PATTERN.matcher(string).matches()) { 613 // TODO(lowasser): could be potentially optimized, but only with 614 // extensive testing 615 try { 616 return Float.parseFloat(string); 617 } catch (NumberFormatException e) { 618 // Float.parseFloat has changed specs several times, so fall through 619 // gracefully 620 } 621 } 622 return null; 623 } 624}