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