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