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
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 @Override
397 public int compare(short[] left, short[] right) {
398 int minLength = Math.min(left.length, right.length);
399 for (int i = 0; i < minLength; i++) {
400 int result = Shorts.compare(left[i], right[i]);
401 if (result != 0) {
402 return result;
403 }
404 }
405 return left.length - right.length;
406 }
407 }
408
409 /**
410 * Copies a collection of {@code Short} instances into a new array of
411 * primitive {@code short} values.
412 *
413 * <p>Elements are copied from the argument collection as if by {@code
414 * collection.toArray()}. Calling this method is as thread-safe as calling
415 * that method.
416 *
417 * @param collection a collection of {@code Short} objects
418 * @return an array containing the same values as {@code collection}, in the
419 * same order, converted to primitives
420 * @throws NullPointerException if {@code collection} or any of its elements
421 * is null
422 */
423 public static short[] toArray(Collection<Short> collection) {
424 if (collection instanceof ShortArrayAsList) {
425 return ((ShortArrayAsList) collection).toShortArray();
426 }
427
428 Object[] boxedArray = collection.toArray();
429 int len = boxedArray.length;
430 short[] array = new short[len];
431 for (int i = 0; i < len; i++) {
432 array[i] = (Short) boxedArray[i];
433 }
434 return array;
435 }
436
437 /**
438 * Returns a fixed-size list backed by the specified array, similar to {@link
439 * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
440 * but any attempt to set a value to {@code null} will result in a {@link
441 * NullPointerException}.
442 *
443 * <p>The returned list maintains the values, but not the identities, of
444 * {@code Short} objects written to or read from it. For example, whether
445 * {@code list.get(0) == list.get(0)} is true for the returned list is
446 * unspecified.
447 *
448 * @param backingArray the array to back the list
449 * @return a list view of the array
450 */
451 public static List<Short> asList(short... backingArray) {
452 if (backingArray.length == 0) {
453 return Collections.emptyList();
454 }
455 return new ShortArrayAsList(backingArray);
456 }
457
458 @GwtCompatible
459 private static class ShortArrayAsList extends AbstractList<Short>
460 implements RandomAccess, Serializable {
461 final short[] array;
462 final int start;
463 final int end;
464
465 ShortArrayAsList(short[] array) {
466 this(array, 0, array.length);
467 }
468
469 ShortArrayAsList(short[] array, int start, int end) {
470 this.array = array;
471 this.start = start;
472 this.end = end;
473 }
474
475 @Override public int size() {
476 return end - start;
477 }
478
479 @Override public boolean isEmpty() {
480 return false;
481 }
482
483 @Override public Short get(int index) {
484 checkElementIndex(index, size());
485 return array[start + index];
486 }
487
488 @Override public boolean contains(Object target) {
489 // Overridden to prevent a ton of boxing
490 return (target instanceof Short)
491 && Shorts.indexOf(array, (Short) target, start, end) != -1;
492 }
493
494 @Override public int indexOf(Object target) {
495 // Overridden to prevent a ton of boxing
496 if (target instanceof Short) {
497 int i = Shorts.indexOf(array, (Short) target, start, end);
498 if (i >= 0) {
499 return i - start;
500 }
501 }
502 return -1;
503 }
504
505 @Override public int lastIndexOf(Object target) {
506 // Overridden to prevent a ton of boxing
507 if (target instanceof Short) {
508 int i = Shorts.lastIndexOf(array, (Short) target, start, end);
509 if (i >= 0) {
510 return i - start;
511 }
512 }
513 return -1;
514 }
515
516 @Override public Short set(int index, Short element) {
517 checkElementIndex(index, size());
518 short oldValue = array[start + index];
519 array[start + index] = element;
520 return oldValue;
521 }
522
523 @Override public List<Short> subList(int fromIndex, int toIndex) {
524 int size = size();
525 checkPositionIndexes(fromIndex, toIndex, size);
526 if (fromIndex == toIndex) {
527 return Collections.emptyList();
528 }
529 return new ShortArrayAsList(array, start + fromIndex, start + toIndex);
530 }
531
532 @Override public boolean equals(Object object) {
533 if (object == this) {
534 return true;
535 }
536 if (object instanceof ShortArrayAsList) {
537 ShortArrayAsList that = (ShortArrayAsList) object;
538 int size = size();
539 if (that.size() != size) {
540 return false;
541 }
542 for (int i = 0; i < size; i++) {
543 if (array[start + i] != that.array[that.start + i]) {
544 return false;
545 }
546 }
547 return true;
548 }
549 return super.equals(object);
550 }
551
552 @Override public int hashCode() {
553 int result = 1;
554 for (int i = start; i < end; i++) {
555 result = 31 * result + Shorts.hashCode(array[i]);
556 }
557 return result;
558 }
559
560 @Override public String toString() {
561 StringBuilder builder = new StringBuilder(size() * 6);
562 builder.append('[').append(array[start]);
563 for (int i = start + 1; i < end; i++) {
564 builder.append(", ").append(array[i]);
565 }
566 return builder.append(']').toString();
567 }
568
569 short[] toShortArray() {
570 // Arrays.copyOfRange() requires Java 6
571 int size = size();
572 short[] result = new short[size];
573 System.arraycopy(array, start, result, 0, size);
574 return result;
575 }
576
577 private static final long serialVersionUID = 0;
578 }
579 }