1 /* 2 * Copyright (C) 2008 The Guava Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.common.primitives; 18 19 import static com.google.common.base.Preconditions.checkArgument; 20 import static com.google.common.base.Preconditions.checkElementIndex; 21 import static com.google.common.base.Preconditions.checkNotNull; 22 import static com.google.common.base.Preconditions.checkPositionIndexes; 23 24 import com.google.common.annotations.GwtCompatible; 25 import com.google.common.annotations.GwtIncompatible; 26 27 import java.io.Serializable; 28 import java.util.AbstractList; 29 import java.util.Arrays; 30 import java.util.Collection; 31 import java.util.Collections; 32 import java.util.Comparator; 33 import java.util.List; 34 import java.util.RandomAccess; 35 36 /** 37 * Static utility methods pertaining to {@code short} primitives, that are not 38 * already found in either {@link Short} or {@link Arrays}. 39 * 40 * @author Kevin Bourrillion 41 * @since 1.0 42 */ 43 @GwtCompatible(emulated = true) 44 public final class Shorts { Shorts()45 private Shorts() {} 46 47 /** 48 * The number of bytes required to represent a primitive {@code short} 49 * value. 50 */ 51 public static final int BYTES = Short.SIZE / Byte.SIZE; 52 53 /** 54 * The largest power of two that can be represented as a {@code short}. 55 * 56 * @since 10.0 57 */ 58 public static final short MAX_POWER_OF_TWO = 1 << (Short.SIZE - 2); 59 60 /** 61 * Returns a hash code for {@code value}; equal to the result of invoking 62 * {@code ((Short) value).hashCode()}. 63 * 64 * @param value a primitive {@code short} value 65 * @return a hash code for the value 66 */ hashCode(short value)67 public static int hashCode(short value) { 68 return value; 69 } 70 71 /** 72 * Returns the {@code short} value that is equal to {@code value}, if 73 * possible. 74 * 75 * @param value any value in the range of the {@code short} type 76 * @return the {@code short} value that equals {@code value} 77 * @throws IllegalArgumentException if {@code value} is greater than {@link 78 * Short#MAX_VALUE} or less than {@link Short#MIN_VALUE} 79 */ checkedCast(long value)80 public static short checkedCast(long value) { 81 short result = (short) value; 82 checkArgument(result == value, "Out of range: %s", value); 83 return result; 84 } 85 86 /** 87 * Returns the {@code short} nearest in value to {@code value}. 88 * 89 * @param value any {@code long} value 90 * @return the same value cast to {@code short} if it is in the range of the 91 * {@code short} type, {@link Short#MAX_VALUE} if it is too large, 92 * or {@link Short#MIN_VALUE} if it is too small 93 */ saturatedCast(long value)94 public static short saturatedCast(long value) { 95 if (value > Short.MAX_VALUE) { 96 return Short.MAX_VALUE; 97 } 98 if (value < Short.MIN_VALUE) { 99 return Short.MIN_VALUE; 100 } 101 return (short) value; 102 } 103 104 /** 105 * Compares the two specified {@code short} values. The sign of the value 106 * returned is the same as that of {@code ((Short) a).compareTo(b)}. 107 * 108 * @param a the first {@code short} to compare 109 * @param b the second {@code short} to compare 110 * @return a negative value if {@code a} is less than {@code b}; a positive 111 * value if {@code a} is greater than {@code b}; or zero if they are equal 112 */ compare(short a, short b)113 public static int compare(short a, short b) { 114 return a - b; // safe due to restricted range 115 } 116 117 /** 118 * Returns {@code true} if {@code target} is present as an element anywhere in 119 * {@code array}. 120 * 121 * @param array an array of {@code short} values, possibly empty 122 * @param target a primitive {@code short} value 123 * @return {@code true} if {@code array[i] == target} for some value of {@code 124 * i} 125 */ contains(short[] array, short target)126 public static boolean contains(short[] array, short target) { 127 for (short value : array) { 128 if (value == target) { 129 return true; 130 } 131 } 132 return false; 133 } 134 135 /** 136 * Returns the index of the first appearance of the value {@code target} in 137 * {@code array}. 138 * 139 * @param array an array of {@code short} values, possibly empty 140 * @param target a primitive {@code short} value 141 * @return the least index {@code i} for which {@code array[i] == target}, or 142 * {@code -1} if no such index exists. 143 */ indexOf(short[] array, short target)144 public static int indexOf(short[] array, short target) { 145 return indexOf(array, target, 0, array.length); 146 } 147 148 // TODO(kevinb): consider making this public indexOf( short[] array, short target, int start, int end)149 private static int indexOf( 150 short[] array, short target, int start, int end) { 151 for (int i = start; i < end; i++) { 152 if (array[i] == target) { 153 return i; 154 } 155 } 156 return -1; 157 } 158 159 /** 160 * Returns the start position of the first occurrence of the specified {@code 161 * target} within {@code array}, or {@code -1} if there is no such occurrence. 162 * 163 * <p>More formally, returns the lowest index {@code i} such that {@code 164 * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly 165 * the same elements as {@code target}. 166 * 167 * @param array the array to search for the sequence {@code target} 168 * @param target the array to search for as a sub-sequence of {@code array} 169 */ indexOf(short[] array, short[] target)170 public static int indexOf(short[] array, short[] target) { 171 checkNotNull(array, "array"); 172 checkNotNull(target, "target"); 173 if (target.length == 0) { 174 return 0; 175 } 176 177 outer: 178 for (int i = 0; i < array.length - target.length + 1; i++) { 179 for (int j = 0; j < target.length; j++) { 180 if (array[i + j] != target[j]) { 181 continue outer; 182 } 183 } 184 return i; 185 } 186 return -1; 187 } 188 189 /** 190 * Returns the index of the last appearance of the value {@code target} in 191 * {@code array}. 192 * 193 * @param array an array of {@code short} values, possibly empty 194 * @param target a primitive {@code short} value 195 * @return the greatest index {@code i} for which {@code array[i] == target}, 196 * or {@code -1} if no such index exists. 197 */ lastIndexOf(short[] array, short target)198 public static int lastIndexOf(short[] array, short target) { 199 return lastIndexOf(array, target, 0, array.length); 200 } 201 202 // TODO(kevinb): consider making this public lastIndexOf( short[] array, short target, int start, int end)203 private static int lastIndexOf( 204 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 218 * every other value in the array 219 * @throws IllegalArgumentException if {@code array} is empty 220 */ min(short... array)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 237 * every other value in the array 238 * @throws IllegalArgumentException if {@code array} is empty 239 */ max(short... array)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 values from each provided array combined into a single array. 253 * For example, {@code concat(new short[] {a, b}, new short[] {}, new 254 * short[] {c}} returns the array {@code {a, b, c}}. 255 * 256 * @param arrays zero or more {@code short} arrays 257 * @return a single array containing all the values from the source arrays, in 258 * order 259 */ concat(short[]... arrays)260 public static short[] concat(short[]... arrays) { 261 int length = 0; 262 for (short[] array : arrays) { 263 length += array.length; 264 } 265 short[] result = new short[length]; 266 int pos = 0; 267 for (short[] array : arrays) { 268 System.arraycopy(array, 0, result, pos, array.length); 269 pos += array.length; 270 } 271 return result; 272 } 273 274 /** 275 * Returns a big-endian representation of {@code value} in a 2-element byte 276 * array; equivalent to {@code 277 * ByteBuffer.allocate(2).putShort(value).array()}. For example, the input 278 * value {@code (short) 0x1234} would yield the byte array {@code {0x12, 279 * 0x34}}. 280 * 281 * <p>If you need to convert and concatenate several values (possibly even of 282 * different types), use a shared {@link java.nio.ByteBuffer} instance, or use 283 * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable 284 * buffer. 285 */ 286 @GwtIncompatible("doesn't work") toByteArray(short value)287 public static byte[] toByteArray(short value) { 288 return new byte[] { 289 (byte) (value >> 8), 290 (byte) value}; 291 } 292 293 /** 294 * Returns the {@code short} value whose big-endian representation is 295 * stored in the first 2 bytes of {@code bytes}; equivalent to {@code 296 * ByteBuffer.wrap(bytes).getShort()}. For example, the input byte array 297 * {@code {0x54, 0x32}} would yield the {@code short} value {@code 0x5432}. 298 * 299 * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that 300 * library exposes much more flexibility at little cost in readability. 301 * 302 * @throws IllegalArgumentException if {@code bytes} has fewer than 2 303 * elements 304 */ 305 @GwtIncompatible("doesn't work") fromByteArray(byte[] bytes)306 public static short fromByteArray(byte[] bytes) { 307 checkArgument(bytes.length >= BYTES, 308 "array too small: %s < %s", bytes.length, BYTES); 309 return fromBytes(bytes[0], bytes[1]); 310 } 311 312 /** 313 * Returns the {@code short} value whose byte representation is the given 2 314 * bytes, in big-endian order; equivalent to {@code Shorts.fromByteArray(new 315 * byte[] {b1, b2})}. 316 * 317 * @since 7.0 318 */ 319 @GwtIncompatible("doesn't work") fromBytes(byte b1, byte b2)320 public static short fromBytes(byte b1, byte b2) { 321 return (short) ((b1 << 8) | (b2 & 0xFF)); 322 } 323 324 /** 325 * Returns an array containing the same values as {@code array}, but 326 * guaranteed to be of a specified minimum length. If {@code array} already 327 * has a length of at least {@code minLength}, it is returned directly. 328 * Otherwise, a new array of size {@code minLength + padding} is returned, 329 * containing the values of {@code array}, and zeroes in the remaining places. 330 * 331 * @param array the source array 332 * @param minLength the minimum length the returned array must guarantee 333 * @param padding an extra amount to "grow" the array by if growth is 334 * necessary 335 * @throws IllegalArgumentException if {@code minLength} or {@code padding} is 336 * negative 337 * @return an array containing the values of {@code array}, with guaranteed 338 * minimum length {@code minLength} 339 */ ensureCapacity( short[] array, int minLength, int padding)340 public static short[] ensureCapacity( 341 short[] array, int minLength, int padding) { 342 checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); 343 checkArgument(padding >= 0, "Invalid padding: %s", padding); 344 return (array.length < minLength) 345 ? copyOf(array, minLength + padding) 346 : array; 347 } 348 349 // Arrays.copyOf() requires Java 6 copyOf(short[] original, int length)350 private static short[] copyOf(short[] original, int length) { 351 short[] copy = new short[length]; 352 System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); 353 return copy; 354 } 355 356 /** 357 * Returns a string containing the supplied {@code short} values separated 358 * by {@code separator}. For example, {@code join("-", (short) 1, (short) 2, 359 * (short) 3)} returns the string {@code "1-2-3"}. 360 * 361 * @param separator the text that should appear between consecutive values in 362 * the resulting string (but not at the start or end) 363 * @param array an array of {@code short} values, possibly empty 364 */ join(String separator, short... array)365 public static String join(String separator, short... array) { 366 checkNotNull(separator); 367 if (array.length == 0) { 368 return ""; 369 } 370 371 // For pre-sizing a builder, just get the right order of magnitude 372 StringBuilder builder = new StringBuilder(array.length * 6); 373 builder.append(array[0]); 374 for (int i = 1; i < array.length; i++) { 375 builder.append(separator).append(array[i]); 376 } 377 return builder.toString(); 378 } 379 380 /** 381 * Returns a comparator that compares two {@code short} arrays 382 * lexicographically. That is, it compares, using {@link 383 * #compare(short, short)}), the first pair of values that follow any 384 * common prefix, or when one array is a prefix of the other, treats the 385 * shorter array as the lesser. For example, {@code [] < [(short) 1] < 386 * [(short) 1, (short) 2] < [(short) 2]}. 387 * 388 * <p>The returned comparator is inconsistent with {@link 389 * Object#equals(Object)} (since arrays support only identity equality), but 390 * it is consistent with {@link Arrays#equals(short[], short[])}. 391 * 392 * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> 393 * Lexicographical order article at Wikipedia</a> 394 * @since 2.0 395 */ lexicographicalComparator()396 public static Comparator<short[]> lexicographicalComparator() { 397 return LexicographicalComparator.INSTANCE; 398 } 399 400 private enum LexicographicalComparator implements Comparator<short[]> { 401 INSTANCE; 402 403 @Override compare(short[] left, short[] right)404 public int compare(short[] left, short[] right) { 405 int minLength = Math.min(left.length, right.length); 406 for (int i = 0; i < minLength; i++) { 407 int result = Shorts.compare(left[i], right[i]); 408 if (result != 0) { 409 return result; 410 } 411 } 412 return left.length - right.length; 413 } 414 } 415 416 /** 417 * Copies a collection of {@code Short} instances into a new array of 418 * primitive {@code short} values. 419 * 420 * <p>Elements are copied from the argument collection as if by {@code 421 * collection.toArray()}. Calling this method is as thread-safe as calling 422 * that method. 423 * 424 * @param collection a collection of {@code Short} objects 425 * @return an array containing the same values as {@code collection}, in the 426 * same order, converted to primitives 427 * @throws NullPointerException if {@code collection} or any of its elements 428 * is null 429 */ toArray(Collection<Short> collection)430 public static short[] toArray(Collection<Short> collection) { 431 if (collection instanceof ShortArrayAsList) { 432 return ((ShortArrayAsList) collection).toShortArray(); 433 } 434 435 Object[] boxedArray = collection.toArray(); 436 int len = boxedArray.length; 437 short[] array = new short[len]; 438 for (int i = 0; i < len; i++) { 439 // checkNotNull for GWT (do not optimize) 440 array[i] = (Short) checkNotNull(boxedArray[i]); 441 } 442 return array; 443 } 444 445 /** 446 * Returns a fixed-size list backed by the specified array, similar to {@link 447 * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, 448 * but any attempt to set a value to {@code null} will result in a {@link 449 * NullPointerException}. 450 * 451 * <p>The returned list maintains the values, but not the identities, of 452 * {@code Short} objects written to or read from it. For example, whether 453 * {@code list.get(0) == list.get(0)} is true for the returned list is 454 * unspecified. 455 * 456 * @param backingArray the array to back the list 457 * @return a list view of the array 458 */ asList(short... backingArray)459 public static List<Short> asList(short... backingArray) { 460 if (backingArray.length == 0) { 461 return Collections.emptyList(); 462 } 463 return new ShortArrayAsList(backingArray); 464 } 465 466 @GwtCompatible 467 private static class ShortArrayAsList extends AbstractList<Short> 468 implements RandomAccess, Serializable { 469 final short[] array; 470 final int start; 471 final int end; 472 ShortArrayAsList(short[] array)473 ShortArrayAsList(short[] array) { 474 this(array, 0, array.length); 475 } 476 ShortArrayAsList(short[] array, int start, int end)477 ShortArrayAsList(short[] array, int start, int end) { 478 this.array = array; 479 this.start = start; 480 this.end = end; 481 } 482 size()483 @Override public int size() { 484 return end - start; 485 } 486 isEmpty()487 @Override public boolean isEmpty() { 488 return false; 489 } 490 get(int index)491 @Override public Short get(int index) { 492 checkElementIndex(index, size()); 493 return array[start + index]; 494 } 495 contains(Object target)496 @Override public boolean contains(Object target) { 497 // Overridden to prevent a ton of boxing 498 return (target instanceof Short) 499 && Shorts.indexOf(array, (Short) target, start, end) != -1; 500 } 501 indexOf(Object target)502 @Override public int indexOf(Object target) { 503 // Overridden to prevent a ton of boxing 504 if (target instanceof Short) { 505 int i = Shorts.indexOf(array, (Short) target, start, end); 506 if (i >= 0) { 507 return i - start; 508 } 509 } 510 return -1; 511 } 512 lastIndexOf(Object target)513 @Override public int lastIndexOf(Object target) { 514 // Overridden to prevent a ton of boxing 515 if (target instanceof Short) { 516 int i = Shorts.lastIndexOf(array, (Short) target, start, end); 517 if (i >= 0) { 518 return i - start; 519 } 520 } 521 return -1; 522 } 523 set(int index, Short element)524 @Override public Short set(int index, Short element) { 525 checkElementIndex(index, size()); 526 short oldValue = array[start + index]; 527 array[start + index] = checkNotNull(element); // checkNotNull for GWT (do not optimize) 528 return oldValue; 529 } 530 subList(int fromIndex, int toIndex)531 @Override public List<Short> subList(int fromIndex, int toIndex) { 532 int size = size(); 533 checkPositionIndexes(fromIndex, toIndex, size); 534 if (fromIndex == toIndex) { 535 return Collections.emptyList(); 536 } 537 return new ShortArrayAsList(array, start + fromIndex, start + toIndex); 538 } 539 equals(Object object)540 @Override public boolean equals(Object object) { 541 if (object == this) { 542 return true; 543 } 544 if (object instanceof ShortArrayAsList) { 545 ShortArrayAsList that = (ShortArrayAsList) object; 546 int size = size(); 547 if (that.size() != size) { 548 return false; 549 } 550 for (int i = 0; i < size; i++) { 551 if (array[start + i] != that.array[that.start + i]) { 552 return false; 553 } 554 } 555 return true; 556 } 557 return super.equals(object); 558 } 559 hashCode()560 @Override public int hashCode() { 561 int result = 1; 562 for (int i = start; i < end; i++) { 563 result = 31 * result + Shorts.hashCode(array[i]); 564 } 565 return result; 566 } 567 toString()568 @Override public String toString() { 569 StringBuilder builder = new StringBuilder(size() * 6); 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 toShortArray()577 short[] toShortArray() { 578 // Arrays.copyOfRange() requires Java 6 579 int size = size(); 580 short[] result = new short[size]; 581 System.arraycopy(array, start, result, 0, size); 582 return result; 583 } 584 585 private static final long serialVersionUID = 0; 586 } 587 } 588