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; 021 022import com.google.common.annotations.Beta; 023import com.google.common.annotations.GwtCompatible; 024import com.google.common.annotations.GwtIncompatible; 025import com.google.common.base.Converter; 026import java.io.Serializable; 027import java.util.AbstractList; 028import java.util.Arrays; 029import java.util.Collection; 030import java.util.Collections; 031import java.util.Comparator; 032import java.util.List; 033import java.util.RandomAccess; 034import org.checkerframework.checker.nullness.compatqual.NullableDecl; 035 036/** 037 * Static utility methods pertaining to {@code short} primitives, that are not already found in 038 * either {@link Short} or {@link Arrays}. 039 * 040 * <p>See the Guava User Guide article on <a 041 * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>. 042 * 043 * @author Kevin Bourrillion 044 * @since 1.0 045 */ 046@GwtCompatible(emulated = true) 047public final class Shorts { 048 private Shorts() {} 049 050 /** 051 * The number of bytes required to represent a primitive {@code short} value. 052 * 053 * <p><b>Java 8 users:</b> use {@link Short#BYTES} instead. 054 */ 055 public static final int BYTES = Short.SIZE / Byte.SIZE; 056 057 /** 058 * The largest power of two that can be represented as a {@code short}. 059 * 060 * @since 10.0 061 */ 062 public static final short MAX_POWER_OF_TWO = 1 << (Short.SIZE - 2); 063 064 /** 065 * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Short) 066 * value).hashCode()}. 067 * 068 * <p><b>Java 8 users:</b> use {@link Short#hashCode(short)} instead. 069 * 070 * @param value a primitive {@code short} value 071 * @return a hash code for the value 072 */ 073 public static int hashCode(short value) { 074 return value; 075 } 076 077 /** 078 * Returns the {@code short} value that is equal to {@code value}, if possible. 079 * 080 * @param value any value in the range of the {@code short} type 081 * @return the {@code short} value that equals {@code value} 082 * @throws IllegalArgumentException if {@code value} is greater than {@link Short#MAX_VALUE} or 083 * less than {@link Short#MIN_VALUE} 084 */ 085 public static short checkedCast(long value) { 086 short result = (short) value; 087 checkArgument(result == value, "Out of range: %s", value); 088 return result; 089 } 090 091 /** 092 * Returns the {@code short} nearest in value to {@code value}. 093 * 094 * @param value any {@code long} value 095 * @return the same value cast to {@code short} if it is in the range of the {@code short} type, 096 * {@link Short#MAX_VALUE} if it is too large, or {@link Short#MIN_VALUE} if it is too small 097 */ 098 public static short saturatedCast(long value) { 099 if (value > Short.MAX_VALUE) { 100 return Short.MAX_VALUE; 101 } 102 if (value < Short.MIN_VALUE) { 103 return Short.MIN_VALUE; 104 } 105 return (short) value; 106 } 107 108 /** 109 * Compares the two specified {@code short} values. The sign of the value returned is the same as 110 * that of {@code ((Short) a).compareTo(b)}. 111 * 112 * <p><b>Note for Java 7 and later:</b> this method should be treated as deprecated; use the 113 * equivalent {@link Short#compare} method instead. 114 * 115 * @param a the first {@code short} to compare 116 * @param b the second {@code short} to compare 117 * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is 118 * greater than {@code b}; or zero if they are equal 119 */ 120 public static int compare(short a, short b) { 121 return a - b; // safe due to restricted range 122 } 123 124 /** 125 * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}. 126 * 127 * @param array an array of {@code short} values, possibly empty 128 * @param target a primitive {@code short} value 129 * @return {@code true} if {@code array[i] == target} for some value of {@code i} 130 */ 131 public static boolean contains(short[] array, short target) { 132 for (short value : array) { 133 if (value == target) { 134 return true; 135 } 136 } 137 return false; 138 } 139 140 /** 141 * Returns the index of the first appearance of the value {@code target} in {@code array}. 142 * 143 * @param array an array of {@code short} values, possibly empty 144 * @param target a primitive {@code short} value 145 * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no 146 * such index exists. 147 */ 148 public static int indexOf(short[] array, short target) { 149 return indexOf(array, target, 0, array.length); 150 } 151 152 // TODO(kevinb): consider making this public 153 private static int indexOf(short[] array, short target, int start, int end) { 154 for (int i = start; i < end; i++) { 155 if (array[i] == target) { 156 return i; 157 } 158 } 159 return -1; 160 } 161 162 /** 163 * Returns the start position of the first occurrence of the specified {@code target} within 164 * {@code array}, or {@code -1} if there is no such occurrence. 165 * 166 * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array, 167 * i, i + target.length)} contains exactly the same elements as {@code target}. 168 * 169 * @param array the array to search for the sequence {@code target} 170 * @param target the array to search for as a sub-sequence of {@code array} 171 */ 172 public static int indexOf(short[] array, short[] target) { 173 checkNotNull(array, "array"); 174 checkNotNull(target, "target"); 175 if (target.length == 0) { 176 return 0; 177 } 178 179 outer: 180 for (int i = 0; i < array.length - target.length + 1; i++) { 181 for (int j = 0; j < target.length; j++) { 182 if (array[i + j] != target[j]) { 183 continue outer; 184 } 185 } 186 return i; 187 } 188 return -1; 189 } 190 191 /** 192 * Returns the index of the last appearance of the value {@code target} in {@code array}. 193 * 194 * @param array an array of {@code short} values, possibly empty 195 * @param target a primitive {@code short} value 196 * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no 197 * such index exists. 198 */ 199 public static int lastIndexOf(short[] array, short target) { 200 return lastIndexOf(array, target, 0, array.length); 201 } 202 203 // TODO(kevinb): consider making this public 204 private static int lastIndexOf(short[] array, short target, int start, int end) { 205 for (int i = end - 1; i >= start; i--) { 206 if (array[i] == target) { 207 return i; 208 } 209 } 210 return -1; 211 } 212 213 /** 214 * Returns the least value present in {@code array}. 215 * 216 * @param array a <i>nonempty</i> array of {@code short} values 217 * @return the value present in {@code array} that is less than or equal to every other value in 218 * the array 219 * @throws IllegalArgumentException if {@code array} is empty 220 */ 221 public static short min(short... array) { 222 checkArgument(array.length > 0); 223 short min = array[0]; 224 for (int i = 1; i < array.length; i++) { 225 if (array[i] < min) { 226 min = array[i]; 227 } 228 } 229 return min; 230 } 231 232 /** 233 * Returns the greatest value present in {@code array}. 234 * 235 * @param array a <i>nonempty</i> array of {@code short} values 236 * @return the value present in {@code array} that is greater than or equal to every other value 237 * in the array 238 * @throws IllegalArgumentException if {@code array} is empty 239 */ 240 public static short max(short... array) { 241 checkArgument(array.length > 0); 242 short max = array[0]; 243 for (int i = 1; i < array.length; i++) { 244 if (array[i] > max) { 245 max = array[i]; 246 } 247 } 248 return max; 249 } 250 251 /** 252 * Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}. 253 * 254 * <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned 255 * unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if {@code 256 * value} is greater than {@code max}, {@code max} is returned. 257 * 258 * @param value the {@code short} value to constrain 259 * @param min the lower bound (inclusive) of the range to constrain {@code value} to 260 * @param max the upper bound (inclusive) of the range to constrain {@code value} to 261 * @throws IllegalArgumentException if {@code min > max} 262 * @since 21.0 263 */ 264 @Beta 265 public static short constrainToRange(short value, short min, short max) { 266 checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max); 267 return value < min ? min : value < max ? value : max; 268 } 269 270 /** 271 * Returns the values from each provided array combined into a single array. For example, {@code 272 * concat(new short[] {a, b}, new short[] {}, new short[] {c}} returns the array {@code {a, b, 273 * c}}. 274 * 275 * @param arrays zero or more {@code short} arrays 276 * @return a single array containing all the values from the source arrays, in order 277 */ 278 public static short[] concat(short[]... arrays) { 279 int length = 0; 280 for (short[] array : arrays) { 281 length += array.length; 282 } 283 short[] result = new short[length]; 284 int pos = 0; 285 for (short[] array : arrays) { 286 System.arraycopy(array, 0, result, pos, array.length); 287 pos += array.length; 288 } 289 return result; 290 } 291 292 /** 293 * Returns a big-endian representation of {@code value} in a 2-element byte array; equivalent to 294 * {@code ByteBuffer.allocate(2).putShort(value).array()}. For example, the input value {@code 295 * (short) 0x1234} would yield the byte array {@code {0x12, 0x34}}. 296 * 297 * <p>If you need to convert and concatenate several values (possibly even of different types), 298 * use a shared {@link java.nio.ByteBuffer} instance, or use {@link 299 * com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer. 300 */ 301 @GwtIncompatible // doesn't work 302 public static byte[] toByteArray(short value) { 303 return new byte[] {(byte) (value >> 8), (byte) value}; 304 } 305 306 /** 307 * Returns the {@code short} value whose big-endian representation is stored in the first 2 bytes 308 * of {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getShort()}. For example, the 309 * input byte array {@code {0x54, 0x32}} would yield the {@code short} value {@code 0x5432}. 310 * 311 * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more 312 * flexibility at little cost in readability. 313 * 314 * @throws IllegalArgumentException if {@code bytes} has fewer than 2 elements 315 */ 316 @GwtIncompatible // doesn't work 317 public static short fromByteArray(byte[] bytes) { 318 checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); 319 return fromBytes(bytes[0], bytes[1]); 320 } 321 322 /** 323 * Returns the {@code short} value whose byte representation is the given 2 bytes, in big-endian 324 * order; equivalent to {@code Shorts.fromByteArray(new byte[] {b1, b2})}. 325 * 326 * @since 7.0 327 */ 328 @GwtIncompatible // doesn't work 329 public static short fromBytes(byte b1, byte b2) { 330 return (short) ((b1 << 8) | (b2 & 0xFF)); 331 } 332 333 private static final class ShortConverter extends Converter<String, Short> 334 implements Serializable { 335 static final ShortConverter INSTANCE = new ShortConverter(); 336 337 @Override 338 protected Short doForward(String value) { 339 return Short.decode(value); 340 } 341 342 @Override 343 protected String doBackward(Short value) { 344 return value.toString(); 345 } 346 347 @Override 348 public String toString() { 349 return "Shorts.stringConverter()"; 350 } 351 352 private Object readResolve() { 353 return INSTANCE; 354 } 355 356 private static final long serialVersionUID = 1; 357 } 358 359 /** 360 * Returns a serializable converter object that converts between strings and shorts using {@link 361 * Short#decode} and {@link Short#toString()}. The returned converter throws {@link 362 * NumberFormatException} if the input string is invalid. 363 * 364 * <p><b>Warning:</b> please see {@link Short#decode} to understand exactly how strings are 365 * parsed. For example, the string {@code "0123"} is treated as <i>octal</i> and converted to the 366 * value {@code 83}. 367 * 368 * @since 16.0 369 */ 370 @Beta 371 public static Converter<String, Short> stringConverter() { 372 return ShortConverter.INSTANCE; 373 } 374 375 /** 376 * Returns an array containing the same values as {@code array}, but guaranteed to be of a 377 * specified minimum length. If {@code array} already has a length of at least {@code minLength}, 378 * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is 379 * returned, containing the values of {@code array}, and zeroes in the remaining places. 380 * 381 * @param array the source array 382 * @param minLength the minimum length the returned array must guarantee 383 * @param padding an extra amount to "grow" the array by if growth is necessary 384 * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative 385 * @return an array containing the values of {@code array}, with guaranteed minimum length {@code 386 * minLength} 387 */ 388 public static short[] ensureCapacity(short[] array, int minLength, int padding) { 389 checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); 390 checkArgument(padding >= 0, "Invalid padding: %s", padding); 391 return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array; 392 } 393 394 /** 395 * Returns a string containing the supplied {@code short} values separated by {@code separator}. 396 * For example, {@code join("-", (short) 1, (short) 2, (short) 3)} returns the string {@code 397 * "1-2-3"}. 398 * 399 * @param separator the text that should appear between consecutive values in the resulting string 400 * (but not at the start or end) 401 * @param array an array of {@code short} values, possibly empty 402 */ 403 public static String join(String separator, short... array) { 404 checkNotNull(separator); 405 if (array.length == 0) { 406 return ""; 407 } 408 409 // For pre-sizing a builder, just get the right order of magnitude 410 StringBuilder builder = new StringBuilder(array.length * 6); 411 builder.append(array[0]); 412 for (int i = 1; i < array.length; i++) { 413 builder.append(separator).append(array[i]); 414 } 415 return builder.toString(); 416 } 417 418 /** 419 * Returns a comparator that compares two {@code short} arrays <a 420 * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it 421 * compares, using {@link #compare(short, short)}), the first pair of values that follow any 422 * common prefix, or when one array is a prefix of the other, treats the shorter array as the 423 * lesser. For example, {@code [] < [(short) 1] < [(short) 1, (short) 2] < [(short) 2]}. 424 * 425 * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays 426 * support only identity equality), but it is consistent with {@link Arrays#equals(short[], 427 * short[])}. 428 * 429 * @since 2.0 430 */ 431 public static Comparator<short[]> lexicographicalComparator() { 432 return LexicographicalComparator.INSTANCE; 433 } 434 435 private enum LexicographicalComparator implements Comparator<short[]> { 436 INSTANCE; 437 438 @Override 439 public int compare(short[] left, short[] right) { 440 int minLength = Math.min(left.length, right.length); 441 for (int i = 0; i < minLength; i++) { 442 int result = Shorts.compare(left[i], right[i]); 443 if (result != 0) { 444 return result; 445 } 446 } 447 return left.length - right.length; 448 } 449 450 @Override 451 public String toString() { 452 return "Shorts.lexicographicalComparator()"; 453 } 454 } 455 456 /** 457 * Sorts the elements of {@code array} in descending order. 458 * 459 * @since 23.1 460 */ 461 public static void sortDescending(short[] array) { 462 checkNotNull(array); 463 sortDescending(array, 0, array.length); 464 } 465 466 /** 467 * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} 468 * exclusive in descending order. 469 * 470 * @since 23.1 471 */ 472 public static void sortDescending(short[] array, int fromIndex, int toIndex) { 473 checkNotNull(array); 474 checkPositionIndexes(fromIndex, toIndex, array.length); 475 Arrays.sort(array, fromIndex, toIndex); 476 reverse(array, fromIndex, toIndex); 477 } 478 479 /** 480 * Reverses the elements of {@code array}. This is equivalent to {@code 481 * Collections.reverse(Shorts.asList(array))}, but is likely to be more efficient. 482 * 483 * @since 23.1 484 */ 485 public static void reverse(short[] array) { 486 checkNotNull(array); 487 reverse(array, 0, array.length); 488 } 489 490 /** 491 * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} 492 * exclusive. This is equivalent to {@code 493 * Collections.reverse(Shorts.asList(array).subList(fromIndex, toIndex))}, but is likely to be 494 * more efficient. 495 * 496 * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or 497 * {@code toIndex > fromIndex} 498 * @since 23.1 499 */ 500 public static void reverse(short[] array, int fromIndex, int toIndex) { 501 checkNotNull(array); 502 checkPositionIndexes(fromIndex, toIndex, array.length); 503 for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) { 504 short tmp = array[i]; 505 array[i] = array[j]; 506 array[j] = tmp; 507 } 508 } 509 510 /** 511 * Returns an array containing each value of {@code collection}, converted to a {@code short} 512 * value in the manner of {@link Number#shortValue}. 513 * 514 * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}. 515 * Calling this method is as thread-safe as calling that method. 516 * 517 * @param collection a collection of {@code Number} instances 518 * @return an array containing the same values as {@code collection}, in the same order, converted 519 * to primitives 520 * @throws NullPointerException if {@code collection} or any of its elements is null 521 * @since 1.0 (parameter was {@code Collection<Short>} before 12.0) 522 */ 523 public static short[] toArray(Collection<? extends Number> collection) { 524 if (collection instanceof ShortArrayAsList) { 525 return ((ShortArrayAsList) collection).toShortArray(); 526 } 527 528 Object[] boxedArray = collection.toArray(); 529 int len = boxedArray.length; 530 short[] array = new short[len]; 531 for (int i = 0; i < len; i++) { 532 // checkNotNull for GWT (do not optimize) 533 array[i] = ((Number) checkNotNull(boxedArray[i])).shortValue(); 534 } 535 return array; 536 } 537 538 /** 539 * Returns a fixed-size list backed by the specified array, similar to {@link 540 * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to 541 * set a value to {@code null} will result in a {@link NullPointerException}. 542 * 543 * <p>The returned list maintains the values, but not the identities, of {@code Short} objects 544 * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for 545 * the returned list is unspecified. 546 * 547 * @param backingArray the array to back the list 548 * @return a list view of the array 549 */ 550 public static List<Short> asList(short... backingArray) { 551 if (backingArray.length == 0) { 552 return Collections.emptyList(); 553 } 554 return new ShortArrayAsList(backingArray); 555 } 556 557 @GwtCompatible 558 private static class ShortArrayAsList extends AbstractList<Short> 559 implements RandomAccess, Serializable { 560 final short[] array; 561 final int start; 562 final int end; 563 564 ShortArrayAsList(short[] array) { 565 this(array, 0, array.length); 566 } 567 568 ShortArrayAsList(short[] array, int start, int end) { 569 this.array = array; 570 this.start = start; 571 this.end = end; 572 } 573 574 @Override 575 public int size() { 576 return end - start; 577 } 578 579 @Override 580 public boolean isEmpty() { 581 return false; 582 } 583 584 @Override 585 public Short get(int index) { 586 checkElementIndex(index, size()); 587 return array[start + index]; 588 } 589 590 @Override 591 public boolean contains(@NullableDecl Object target) { 592 // Overridden to prevent a ton of boxing 593 return (target instanceof Short) && Shorts.indexOf(array, (Short) target, start, end) != -1; 594 } 595 596 @Override 597 public int indexOf(@NullableDecl Object target) { 598 // Overridden to prevent a ton of boxing 599 if (target instanceof Short) { 600 int i = Shorts.indexOf(array, (Short) target, start, end); 601 if (i >= 0) { 602 return i - start; 603 } 604 } 605 return -1; 606 } 607 608 @Override 609 public int lastIndexOf(@NullableDecl Object target) { 610 // Overridden to prevent a ton of boxing 611 if (target instanceof Short) { 612 int i = Shorts.lastIndexOf(array, (Short) target, start, end); 613 if (i >= 0) { 614 return i - start; 615 } 616 } 617 return -1; 618 } 619 620 @Override 621 public Short set(int index, Short element) { 622 checkElementIndex(index, size()); 623 short oldValue = array[start + index]; 624 // checkNotNull for GWT (do not optimize) 625 array[start + index] = checkNotNull(element); 626 return oldValue; 627 } 628 629 @Override 630 public List<Short> subList(int fromIndex, int toIndex) { 631 int size = size(); 632 checkPositionIndexes(fromIndex, toIndex, size); 633 if (fromIndex == toIndex) { 634 return Collections.emptyList(); 635 } 636 return new ShortArrayAsList(array, start + fromIndex, start + toIndex); 637 } 638 639 @Override 640 public boolean equals(@NullableDecl Object object) { 641 if (object == this) { 642 return true; 643 } 644 if (object instanceof ShortArrayAsList) { 645 ShortArrayAsList that = (ShortArrayAsList) object; 646 int size = size(); 647 if (that.size() != size) { 648 return false; 649 } 650 for (int i = 0; i < size; i++) { 651 if (array[start + i] != that.array[that.start + i]) { 652 return false; 653 } 654 } 655 return true; 656 } 657 return super.equals(object); 658 } 659 660 @Override 661 public int hashCode() { 662 int result = 1; 663 for (int i = start; i < end; i++) { 664 result = 31 * result + Shorts.hashCode(array[i]); 665 } 666 return result; 667 } 668 669 @Override 670 public String toString() { 671 StringBuilder builder = new StringBuilder(size() * 6); 672 builder.append('[').append(array[start]); 673 for (int i = start + 1; i < end; i++) { 674 builder.append(", ").append(array[i]); 675 } 676 return builder.append(']').toString(); 677 } 678 679 short[] toShortArray() { 680 return Arrays.copyOfRange(array, start, end); 681 } 682 683 private static final long serialVersionUID = 0; 684 } 685}