001/*
002 * Copyright (C) 2008 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.primitives;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkElementIndex;
019import static com.google.common.base.Preconditions.checkNotNull;
020import static com.google.common.base.Preconditions.checkPositionIndexes;
021
022import com.google.common.annotations.Beta;
023import com.google.common.annotations.GwtCompatible;
024import com.google.common.annotations.GwtIncompatible;
025import com.google.common.base.Converter;
026import java.io.Serializable;
027import java.util.AbstractList;
028import java.util.Arrays;
029import java.util.Collection;
030import java.util.Collections;
031import java.util.Comparator;
032import java.util.List;
033import java.util.RandomAccess;
034import org.checkerframework.checker.nullness.compatqual.NullableDecl;
035
036/**
037 * Static utility methods pertaining to {@code short} primitives, that are not already found in
038 * either {@link Short} or {@link Arrays}.
039 *
040 * <p>See the Guava User Guide article on <a
041 * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>.
042 *
043 * @author Kevin Bourrillion
044 * @since 1.0
045 */
046@GwtCompatible(emulated = true)
047public final class Shorts extends ShortsMethodsForWeb {
048  private Shorts() {}
049
050  /**
051   * The number of bytes required to represent a primitive {@code short} value.
052   *
053   * <p><b>Java 8 users:</b> use {@link Short#BYTES} instead.
054   */
055  public static final int BYTES = Short.SIZE / Byte.SIZE;
056
057  /**
058   * The largest power of two that can be represented as a {@code short}.
059   *
060   * @since 10.0
061   */
062  public static final short MAX_POWER_OF_TWO = 1 << (Short.SIZE - 2);
063
064  /**
065   * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Short)
066   * value).hashCode()}.
067   *
068   * <p><b>Java 8 users:</b> use {@link Short#hashCode(short)} instead.
069   *
070   * @param value a primitive {@code short} value
071   * @return a hash code for the value
072   */
073  public static int hashCode(short value) {
074    return value;
075  }
076
077  /**
078   * Returns the {@code short} value that is equal to {@code value}, if possible.
079   *
080   * @param value any value in the range of the {@code short} type
081   * @return the {@code short} value that equals {@code value}
082   * @throws IllegalArgumentException if {@code value} is greater than {@link Short#MAX_VALUE} or
083   *     less than {@link Short#MIN_VALUE}
084   */
085  public static short checkedCast(long value) {
086    short result = (short) value;
087    checkArgument(result == value, "Out of range: %s", value);
088    return result;
089  }
090
091  /**
092   * Returns the {@code short} nearest in value to {@code value}.
093   *
094   * @param value any {@code long} value
095   * @return the same value cast to {@code short} if it is in the range of the {@code short} type,
096   *     {@link Short#MAX_VALUE} if it is too large, or {@link Short#MIN_VALUE} if it is too small
097   */
098  public static short saturatedCast(long value) {
099    if (value > Short.MAX_VALUE) {
100      return Short.MAX_VALUE;
101    }
102    if (value < Short.MIN_VALUE) {
103      return Short.MIN_VALUE;
104    }
105    return (short) value;
106  }
107
108  /**
109   * Compares the two specified {@code short} values. The sign of the value returned is the same as
110   * that of {@code ((Short) a).compareTo(b)}.
111   *
112   * <p><b>Note for Java 7 and later:</b> this method should be treated as deprecated; use the
113   * equivalent {@link Short#compare} method instead.
114   *
115   * @param a the first {@code short} to compare
116   * @param b the second {@code short} to compare
117   * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is
118   *     greater than {@code b}; or zero if they are equal
119   */
120  public static int compare(short a, short b) {
121    return a - b; // safe due to restricted range
122  }
123
124  /**
125   * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}.
126   *
127   * @param array an array of {@code short} values, possibly empty
128   * @param target a primitive {@code short} value
129   * @return {@code true} if {@code array[i] == target} for some value of {@code i}
130   */
131  public static boolean contains(short[] array, short target) {
132    for (short value : array) {
133      if (value == target) {
134        return true;
135      }
136    }
137    return false;
138  }
139
140  /**
141   * Returns the index of the first appearance of the value {@code target} in {@code array}.
142   *
143   * @param array an array of {@code short} values, possibly empty
144   * @param target a primitive {@code short} value
145   * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no
146   *     such index exists.
147   */
148  public static int indexOf(short[] array, short target) {
149    return indexOf(array, target, 0, array.length);
150  }
151
152  // TODO(kevinb): consider making this public
153  private static int indexOf(short[] array, short target, int start, int end) {
154    for (int i = start; i < end; i++) {
155      if (array[i] == target) {
156        return i;
157      }
158    }
159    return -1;
160  }
161
162  /**
163   * Returns the start position of the first occurrence of the specified {@code target} within
164   * {@code array}, or {@code -1} if there is no such occurrence.
165   *
166   * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array,
167   * i, i + target.length)} contains exactly the same elements as {@code target}.
168   *
169   * @param array the array to search for the sequence {@code target}
170   * @param target the array to search for as a sub-sequence of {@code array}
171   */
172  public static int indexOf(short[] array, short[] target) {
173    checkNotNull(array, "array");
174    checkNotNull(target, "target");
175    if (target.length == 0) {
176      return 0;
177    }
178
179    outer:
180    for (int i = 0; i < array.length - target.length + 1; i++) {
181      for (int j = 0; j < target.length; j++) {
182        if (array[i + j] != target[j]) {
183          continue outer;
184        }
185      }
186      return i;
187    }
188    return -1;
189  }
190
191  /**
192   * Returns the index of the last appearance of the value {@code target} in {@code array}.
193   *
194   * @param array an array of {@code short} values, possibly empty
195   * @param target a primitive {@code short} value
196   * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no
197   *     such index exists.
198   */
199  public static int lastIndexOf(short[] array, short target) {
200    return lastIndexOf(array, target, 0, array.length);
201  }
202
203  // TODO(kevinb): consider making this public
204  private static int lastIndexOf(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 every other value in
218   *     the array
219   * @throws IllegalArgumentException if {@code array} is empty
220   */
221  @GwtIncompatible(
222      "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.")
223  public static short min(short... array) {
224    checkArgument(array.length > 0);
225    short min = array[0];
226    for (int i = 1; i < array.length; i++) {
227      if (array[i] < min) {
228        min = array[i];
229      }
230    }
231    return min;
232  }
233
234  /**
235   * Returns the greatest value present in {@code array}.
236   *
237   * @param array a <i>nonempty</i> array of {@code short} values
238   * @return the value present in {@code array} that is greater than or equal to every other value
239   *     in the array
240   * @throws IllegalArgumentException if {@code array} is empty
241   */
242  @GwtIncompatible(
243      "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.")
244  public static short max(short... array) {
245    checkArgument(array.length > 0);
246    short max = array[0];
247    for (int i = 1; i < array.length; i++) {
248      if (array[i] > max) {
249        max = array[i];
250      }
251    }
252    return max;
253  }
254
255  /**
256   * Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}.
257   *
258   * <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned
259   * unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if {@code
260   * value} is greater than {@code max}, {@code max} is returned.
261   *
262   * @param value the {@code short} value to constrain
263   * @param min the lower bound (inclusive) of the range to constrain {@code value} to
264   * @param max the upper bound (inclusive) of the range to constrain {@code value} to
265   * @throws IllegalArgumentException if {@code min > max}
266   * @since 21.0
267   */
268  @Beta
269  public static short constrainToRange(short value, short min, short max) {
270    checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max);
271    return value < min ? min : value < max ? value : max;
272  }
273
274  /**
275   * Returns the values from each provided array combined into a single array. For example, {@code
276   * concat(new short[] {a, b}, new short[] {}, new short[] {c}} returns the array {@code {a, b,
277   * c}}.
278   *
279   * @param arrays zero or more {@code short} arrays
280   * @return a single array containing all the values from the source arrays, in order
281   */
282  public static short[] concat(short[]... arrays) {
283    int length = 0;
284    for (short[] array : arrays) {
285      length += array.length;
286    }
287    short[] result = new short[length];
288    int pos = 0;
289    for (short[] array : arrays) {
290      System.arraycopy(array, 0, result, pos, array.length);
291      pos += array.length;
292    }
293    return result;
294  }
295
296  /**
297   * Returns a big-endian representation of {@code value} in a 2-element byte array; equivalent to
298   * {@code ByteBuffer.allocate(2).putShort(value).array()}. For example, the input value {@code
299   * (short) 0x1234} would yield the byte array {@code {0x12, 0x34}}.
300   *
301   * <p>If you need to convert and concatenate several values (possibly even of different types),
302   * use a shared {@link java.nio.ByteBuffer} instance, or use {@link
303   * com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer.
304   */
305  @GwtIncompatible // doesn't work
306  public static byte[] toByteArray(short value) {
307    return new byte[] {(byte) (value >> 8), (byte) value};
308  }
309
310  /**
311   * Returns the {@code short} value whose big-endian representation is stored in the first 2 bytes
312   * of {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getShort()}. For example, the
313   * input byte array {@code {0x54, 0x32}} would yield the {@code short} value {@code 0x5432}.
314   *
315   * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more
316   * flexibility at little cost in readability.
317   *
318   * @throws IllegalArgumentException if {@code bytes} has fewer than 2 elements
319   */
320  @GwtIncompatible // doesn't work
321  public static short fromByteArray(byte[] bytes) {
322    checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES);
323    return fromBytes(bytes[0], bytes[1]);
324  }
325
326  /**
327   * Returns the {@code short} value whose byte representation is the given 2 bytes, in big-endian
328   * order; equivalent to {@code Shorts.fromByteArray(new 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 shorts using {@link
365   * Short#decode} and {@link Short#toString()}. The returned converter throws {@link
366   * NumberFormatException} if the input string is invalid.
367   *
368   * <p><b>Warning:</b> please see {@link Short#decode} to understand exactly how strings are
369   * parsed. For example, the string {@code "0123"} is treated as <i>octal</i> and converted to the
370   * value {@code 83}.
371   *
372   * @since 16.0
373   */
374  @Beta
375  public static Converter<String, Short> stringConverter() {
376    return ShortConverter.INSTANCE;
377  }
378
379  /**
380   * Returns an array containing the same values as {@code array}, but guaranteed to be of a
381   * specified minimum length. If {@code array} already has a length of at least {@code minLength},
382   * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is
383   * returned, containing the values of {@code array}, and zeroes in the remaining places.
384   *
385   * @param array the source array
386   * @param minLength the minimum length the returned array must guarantee
387   * @param padding an extra amount to "grow" the array by if growth is necessary
388   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative
389   * @return an array containing the values of {@code array}, with guaranteed minimum length {@code
390   *     minLength}
391   */
392  public static short[] ensureCapacity(short[] array, int minLength, int padding) {
393    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
394    checkArgument(padding >= 0, "Invalid padding: %s", padding);
395    return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array;
396  }
397
398  /**
399   * Returns a string containing the supplied {@code short} values separated by {@code separator}.
400   * For example, {@code join("-", (short) 1, (short) 2, (short) 3)} returns the string {@code
401   * "1-2-3"}.
402   *
403   * @param separator the text that should appear between consecutive values in the resulting string
404   *     (but not at the start or end)
405   * @param array an array of {@code short} values, possibly empty
406   */
407  public static String join(String separator, short... array) {
408    checkNotNull(separator);
409    if (array.length == 0) {
410      return "";
411    }
412
413    // For pre-sizing a builder, just get the right order of magnitude
414    StringBuilder builder = new StringBuilder(array.length * 6);
415    builder.append(array[0]);
416    for (int i = 1; i < array.length; i++) {
417      builder.append(separator).append(array[i]);
418    }
419    return builder.toString();
420  }
421
422  /**
423   * Returns a comparator that compares two {@code short} arrays <a
424   * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it
425   * compares, using {@link #compare(short, short)}), the first pair of values that follow any
426   * common prefix, or when one array is a prefix of the other, treats the shorter array as the
427   * lesser. For example, {@code [] < [(short) 1] < [(short) 1, (short) 2] < [(short) 2]}.
428   *
429   * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
430   * support only identity equality), but it is consistent with {@link Arrays#equals(short[],
431   * short[])}.
432   *
433   * @since 2.0
434   */
435  public static Comparator<short[]> lexicographicalComparator() {
436    return LexicographicalComparator.INSTANCE;
437  }
438
439  private enum LexicographicalComparator implements Comparator<short[]> {
440    INSTANCE;
441
442    @Override
443    public int compare(short[] left, short[] right) {
444      int minLength = Math.min(left.length, right.length);
445      for (int i = 0; i < minLength; i++) {
446        int result = Shorts.compare(left[i], right[i]);
447        if (result != 0) {
448          return result;
449        }
450      }
451      return left.length - right.length;
452    }
453
454    @Override
455    public String toString() {
456      return "Shorts.lexicographicalComparator()";
457    }
458  }
459
460  /**
461   * Sorts the elements of {@code array} in descending order.
462   *
463   * @since 23.1
464   */
465  public static void sortDescending(short[] array) {
466    checkNotNull(array);
467    sortDescending(array, 0, array.length);
468  }
469
470  /**
471   * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
472   * exclusive in descending order.
473   *
474   * @since 23.1
475   */
476  public static void sortDescending(short[] array, int fromIndex, int toIndex) {
477    checkNotNull(array);
478    checkPositionIndexes(fromIndex, toIndex, array.length);
479    Arrays.sort(array, fromIndex, toIndex);
480    reverse(array, fromIndex, toIndex);
481  }
482
483  /**
484   * Reverses the elements of {@code array}. This is equivalent to {@code
485   * Collections.reverse(Shorts.asList(array))}, but is likely to be more efficient.
486   *
487   * @since 23.1
488   */
489  public static void reverse(short[] array) {
490    checkNotNull(array);
491    reverse(array, 0, array.length);
492  }
493
494  /**
495   * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
496   * exclusive. This is equivalent to {@code
497   * Collections.reverse(Shorts.asList(array).subList(fromIndex, toIndex))}, but is likely to be
498   * more efficient.
499   *
500   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
501   *     {@code toIndex > fromIndex}
502   * @since 23.1
503   */
504  public static void reverse(short[] array, int fromIndex, int toIndex) {
505    checkNotNull(array);
506    checkPositionIndexes(fromIndex, toIndex, array.length);
507    for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) {
508      short tmp = array[i];
509      array[i] = array[j];
510      array[j] = tmp;
511    }
512  }
513
514  /**
515   * Returns an array containing each value of {@code collection}, converted to a {@code short}
516   * value in the manner of {@link Number#shortValue}.
517   *
518   * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}.
519   * Calling this method is as thread-safe as calling that method.
520   *
521   * @param collection a collection of {@code Number} instances
522   * @return an array containing the same values as {@code collection}, in the same order, converted
523   *     to primitives
524   * @throws NullPointerException if {@code collection} or any of its elements is null
525   * @since 1.0 (parameter was {@code Collection<Short>} before 12.0)
526   */
527  public static short[] toArray(Collection<? extends Number> collection) {
528    if (collection instanceof ShortArrayAsList) {
529      return ((ShortArrayAsList) collection).toShortArray();
530    }
531
532    Object[] boxedArray = collection.toArray();
533    int len = boxedArray.length;
534    short[] array = new short[len];
535    for (int i = 0; i < len; i++) {
536      // checkNotNull for GWT (do not optimize)
537      array[i] = ((Number) checkNotNull(boxedArray[i])).shortValue();
538    }
539    return array;
540  }
541
542  /**
543   * Returns a fixed-size list backed by the specified array, similar to {@link
544   * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to
545   * set a value to {@code null} will result in a {@link NullPointerException}.
546   *
547   * <p>The returned list maintains the values, but not the identities, of {@code Short} objects
548   * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
549   * the returned list is unspecified.
550   *
551   * @param backingArray the array to back the list
552   * @return a list view of the array
553   */
554  public static List<Short> asList(short... backingArray) {
555    if (backingArray.length == 0) {
556      return Collections.emptyList();
557    }
558    return new ShortArrayAsList(backingArray);
559  }
560
561  @GwtCompatible
562  private static class ShortArrayAsList extends AbstractList<Short>
563      implements RandomAccess, Serializable {
564    final short[] array;
565    final int start;
566    final int end;
567
568    ShortArrayAsList(short[] array) {
569      this(array, 0, array.length);
570    }
571
572    ShortArrayAsList(short[] array, int start, int end) {
573      this.array = array;
574      this.start = start;
575      this.end = end;
576    }
577
578    @Override
579    public int size() {
580      return end - start;
581    }
582
583    @Override
584    public boolean isEmpty() {
585      return false;
586    }
587
588    @Override
589    public Short get(int index) {
590      checkElementIndex(index, size());
591      return array[start + index];
592    }
593
594    @Override
595    public boolean contains(@NullableDecl Object target) {
596      // Overridden to prevent a ton of boxing
597      return (target instanceof Short) && Shorts.indexOf(array, (Short) target, start, end) != -1;
598    }
599
600    @Override
601    public int indexOf(@NullableDecl Object target) {
602      // Overridden to prevent a ton of boxing
603      if (target instanceof Short) {
604        int i = Shorts.indexOf(array, (Short) target, start, end);
605        if (i >= 0) {
606          return i - start;
607        }
608      }
609      return -1;
610    }
611
612    @Override
613    public int lastIndexOf(@NullableDecl Object target) {
614      // Overridden to prevent a ton of boxing
615      if (target instanceof Short) {
616        int i = Shorts.lastIndexOf(array, (Short) target, start, end);
617        if (i >= 0) {
618          return i - start;
619        }
620      }
621      return -1;
622    }
623
624    @Override
625    public Short set(int index, Short element) {
626      checkElementIndex(index, size());
627      short oldValue = array[start + index];
628      // checkNotNull for GWT (do not optimize)
629      array[start + index] = checkNotNull(element);
630      return oldValue;
631    }
632
633    @Override
634    public List<Short> subList(int fromIndex, int toIndex) {
635      int size = size();
636      checkPositionIndexes(fromIndex, toIndex, size);
637      if (fromIndex == toIndex) {
638        return Collections.emptyList();
639      }
640      return new ShortArrayAsList(array, start + fromIndex, start + toIndex);
641    }
642
643    @Override
644    public boolean equals(@NullableDecl Object object) {
645      if (object == this) {
646        return true;
647      }
648      if (object instanceof ShortArrayAsList) {
649        ShortArrayAsList that = (ShortArrayAsList) object;
650        int size = size();
651        if (that.size() != size) {
652          return false;
653        }
654        for (int i = 0; i < size; i++) {
655          if (array[start + i] != that.array[that.start + i]) {
656            return false;
657          }
658        }
659        return true;
660      }
661      return super.equals(object);
662    }
663
664    @Override
665    public int hashCode() {
666      int result = 1;
667      for (int i = start; i < end; i++) {
668        result = 31 * result + Shorts.hashCode(array[i]);
669      }
670      return result;
671    }
672
673    @Override
674    public String toString() {
675      StringBuilder builder = new StringBuilder(size() * 6);
676      builder.append('[').append(array[start]);
677      for (int i = start + 1; i < end; i++) {
678        builder.append(", ").append(array[i]);
679      }
680      return builder.append(']').toString();
681    }
682
683    short[] toShortArray() {
684      return Arrays.copyOfRange(array, start, end);
685    }
686
687    private static final long serialVersionUID = 0;
688  }
689}