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
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: 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: 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 stored
288 * in the first 2 bytes of {@code bytes}; equivalent to {@code
289 * ByteBuffer.wrap(bytes).getShort()}. For example, the input byte array
290 * {@code {0x12, 0x34}} would yield the {@code short} value {@code 0x1234}.
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 (short) ((bytes[0] << 8) | (bytes[1] & 0xFF));
303 }
304
305 /**
306 * Returns an array containing the same values as {@code array}, but
307 * guaranteed to be of a specified minimum length. If {@code array} already
308 * has a length of at least {@code minLength}, it is returned directly.
309 * Otherwise, a new array of size {@code minLength + padding} is returned,
310 * containing the values of {@code array}, and zeroes in the remaining places.
311 *
312 * @param array the source array
313 * @param minLength the minimum length the returned array must guarantee
314 * @param padding an extra amount to "grow" the array by if growth is
315 * necessary
316 * @throws IllegalArgumentException if {@code minLength} or {@code padding} is
317 * negative
318 * @return an array containing the values of {@code array}, with guaranteed
319 * minimum length {@code minLength}
320 */
321 public static short[] ensureCapacity(
322 short[] array, int minLength, int padding) {
323 checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
324 checkArgument(padding >= 0, "Invalid padding: %s", padding);
325 return (array.length < minLength)
326 ? copyOf(array, minLength + padding)
327 : array;
328 }
329
330 // Arrays.copyOf() requires Java 6
331 private static short[] copyOf(short[] original, int length) {
332 short[] copy = new short[length];
333 System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
334 return copy;
335 }
336
337 /**
338 * Returns a string containing the supplied {@code short} values separated
339 * by {@code separator}. For example, {@code join("-", (short) 1, (short) 2,
340 * (short) 3)} returns the string {@code "1-2-3"}.
341 *
342 * @param separator the text that should appear between consecutive values in
343 * the resulting string (but not at the start or end)
344 * @param array an array of {@code short} values, possibly empty
345 */
346 public static String join(String separator, short... array) {
347 checkNotNull(separator);
348 if (array.length == 0) {
349 return "";
350 }
351
352 // For pre-sizing a builder, just get the right order of magnitude
353 StringBuilder builder = new StringBuilder(array.length * 6);
354 builder.append(array[0]);
355 for (int i = 1; i < array.length; i++) {
356 builder.append(separator).append(array[i]);
357 }
358 return builder.toString();
359 }
360
361 /**
362 * Returns a comparator that compares two {@code short} arrays
363 * lexicographically. That is, it compares, using {@link
364 * #compare(short, short)}), the first pair of values that follow any
365 * common prefix, or when one array is a prefix of the other, treats the
366 * shorter array as the lesser. For example, {@code [] < [(short) 1] <
367 * [(short) 1, (short) 2] < [(short) 2]}.
368 *
369 * <p>The returned comparator is inconsistent with {@link
370 * Object#equals(Object)} (since arrays support only identity equality), but
371 * it is consistent with {@link Arrays#equals(short[], short[])}.
372 *
373 * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
374 * Lexicographical order</a> article at Wikipedia
375 * @since 2
376 */
377 public static Comparator<short[]> lexicographicalComparator() {
378 return LexicographicalComparator.INSTANCE;
379 }
380
381 private enum LexicographicalComparator implements Comparator<short[]> {
382 INSTANCE;
383
384 public int compare(short[] left, short[] right) {
385 int minLength = Math.min(left.length, right.length);
386 for (int i = 0; i < minLength; i++) {
387 int result = Shorts.compare(left[i], right[i]);
388 if (result != 0) {
389 return result;
390 }
391 }
392 return left.length - right.length;
393 }
394 }
395
396 /**
397 * Copies a collection of {@code Short} instances into a new array of
398 * primitive {@code short} values.
399 *
400 * <p>Elements are copied from the argument collection as if by {@code
401 * collection.toArray()}. Calling this method is as thread-safe as calling
402 * that method.
403 *
404 * @param collection a collection of {@code Short} objects
405 * @return an array containing the same values as {@code collection}, in the
406 * same order, converted to primitives
407 * @throws NullPointerException if {@code collection} or any of its elements
408 * is null
409 */
410 public static short[] toArray(Collection<Short> collection) {
411 if (collection instanceof ShortArrayAsList) {
412 return ((ShortArrayAsList) collection).toShortArray();
413 }
414
415 Object[] boxedArray = collection.toArray();
416 int len = boxedArray.length;
417 short[] array = new short[len];
418 for (int i = 0; i < len; i++) {
419 array[i] = (Short) boxedArray[i];
420 }
421 return array;
422 }
423
424 /**
425 * Returns a fixed-size list backed by the specified array, similar to {@link
426 * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
427 * but any attempt to set a value to {@code null} will result in a {@link
428 * NullPointerException}.
429 *
430 * <p>The returned list maintains the values, but not the identities, of
431 * {@code Short} objects written to or read from it. For example, whether
432 * {@code list.get(0) == list.get(0)} is true for the returned list is
433 * unspecified.
434 *
435 * @param backingArray the array to back the list
436 * @return a list view of the array
437 */
438 public static List<Short> asList(short... backingArray) {
439 if (backingArray.length == 0) {
440 return Collections.emptyList();
441 }
442 return new ShortArrayAsList(backingArray);
443 }
444
445 @GwtCompatible
446 private static class ShortArrayAsList extends AbstractList<Short>
447 implements RandomAccess, Serializable {
448 final short[] array;
449 final int start;
450 final int end;
451
452 ShortArrayAsList(short[] array) {
453 this(array, 0, array.length);
454 }
455
456 ShortArrayAsList(short[] array, int start, int end) {
457 this.array = array;
458 this.start = start;
459 this.end = end;
460 }
461
462 @Override public int size() {
463 return end - start;
464 }
465
466 @Override public boolean isEmpty() {
467 return false;
468 }
469
470 @Override public Short get(int index) {
471 checkElementIndex(index, size());
472 return array[start + index];
473 }
474
475 @Override public boolean contains(Object target) {
476 // Overridden to prevent a ton of boxing
477 return (target instanceof Short)
478 && Shorts.indexOf(array, (Short) target, start, end) != -1;
479 }
480
481 @Override public int indexOf(Object target) {
482 // Overridden to prevent a ton of boxing
483 if (target instanceof Short) {
484 int i = Shorts.indexOf(array, (Short) target, start, end);
485 if (i >= 0) {
486 return i - start;
487 }
488 }
489 return -1;
490 }
491
492 @Override public int lastIndexOf(Object target) {
493 // Overridden to prevent a ton of boxing
494 if (target instanceof Short) {
495 int i = Shorts.lastIndexOf(array, (Short) target, start, end);
496 if (i >= 0) {
497 return i - start;
498 }
499 }
500 return -1;
501 }
502
503 @Override public Short set(int index, Short element) {
504 checkElementIndex(index, size());
505 short oldValue = array[start + index];
506 array[start + index] = element;
507 return oldValue;
508 }
509
510 /** In GWT, List and AbstractList do not have the subList method. */
511 @Override public List<Short> subList(int fromIndex, int toIndex) {
512 int size = size();
513 checkPositionIndexes(fromIndex, toIndex, size);
514 if (fromIndex == toIndex) {
515 return Collections.emptyList();
516 }
517 return new ShortArrayAsList(array, start + fromIndex, start + toIndex);
518 }
519
520 @Override public boolean equals(Object object) {
521 if (object == this) {
522 return true;
523 }
524 if (object instanceof ShortArrayAsList) {
525 ShortArrayAsList that = (ShortArrayAsList) object;
526 int size = size();
527 if (that.size() != size) {
528 return false;
529 }
530 for (int i = 0; i < size; i++) {
531 if (array[start + i] != that.array[that.start + i]) {
532 return false;
533 }
534 }
535 return true;
536 }
537 return super.equals(object);
538 }
539
540 @Override public int hashCode() {
541 int result = 1;
542 for (int i = start; i < end; i++) {
543 result = 31 * result + Shorts.hashCode(array[i]);
544 }
545 return result;
546 }
547
548 @Override public String toString() {
549 StringBuilder builder = new StringBuilder(size() * 6);
550 builder.append('[').append(array[start]);
551 for (int i = start + 1; i < end; i++) {
552 builder.append(", ").append(array[i]);
553 }
554 return builder.append(']').toString();
555 }
556
557 short[] toShortArray() {
558 // Arrays.copyOfRange() requires Java 6
559 int size = size();
560 short[] result = new short[size];
561 System.arraycopy(array, start, result, 0, size);
562 return result;
563 }
564
565 private static final long serialVersionUID = 0;
566 }
567 }