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