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