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    if (result != value) {
087      // don't use checkArgument here, to avoid boxing
088      throw new IllegalArgumentException("Out of range: " + value);
089    }
090    return result;
091  }
092
093  /**
094   * Returns the {@code short} nearest in value to {@code value}.
095   *
096   * @param value any {@code long} value
097   * @return the same value cast to {@code short} if it is in the range of the {@code short} type,
098   *     {@link Short#MAX_VALUE} if it is too large, or {@link Short#MIN_VALUE} if it is too small
099   */
100  public static short saturatedCast(long value) {
101    if (value > Short.MAX_VALUE) {
102      return Short.MAX_VALUE;
103    }
104    if (value < Short.MIN_VALUE) {
105      return Short.MIN_VALUE;
106    }
107    return (short) value;
108  }
109
110  /**
111   * Compares the two specified {@code short} values. The sign of the value returned is the same as
112   * that of {@code ((Short) a).compareTo(b)}.
113   *
114   * <p><b>Note for Java 7 and later:</b> this method should be treated as deprecated; use the
115   * equivalent {@link Short#compare} method instead.
116   *
117   * @param a the first {@code short} to compare
118   * @param b the second {@code short} to compare
119   * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is
120   *     greater than {@code b}; or zero if they are equal
121   */
122  public static int compare(short a, short b) {
123    return a - b; // safe due to restricted range
124  }
125
126  /**
127   * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}.
128   *
129   * @param array an array of {@code short} values, possibly empty
130   * @param target a primitive {@code short} value
131   * @return {@code true} if {@code array[i] == target} for some value of {@code
132   *     i}
133   */
134  public static boolean contains(short[] array, short target) {
135    for (short value : array) {
136      if (value == target) {
137        return true;
138      }
139    }
140    return false;
141  }
142
143  /**
144   * Returns the index of the first appearance of the value {@code target} in {@code array}.
145   *
146   * @param array an array of {@code short} values, possibly empty
147   * @param target a primitive {@code short} value
148   * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no
149   *     such index exists.
150   */
151  public static int indexOf(short[] array, short target) {
152    return indexOf(array, target, 0, array.length);
153  }
154
155  // TODO(kevinb): consider making this public
156  private static int indexOf(short[] array, short target, int start, int end) {
157    for (int i = start; i < end; i++) {
158      if (array[i] == target) {
159        return i;
160      }
161    }
162    return -1;
163  }
164
165  /**
166   * Returns the start position of the first occurrence of the specified {@code
167   * target} within {@code array}, or {@code -1} if there is no such occurrence.
168   *
169   * <p>More formally, returns the lowest index {@code i} such that
170   * {@code Arrays.copyOfRange(array, i, i + target.length)} contains exactly the same elements as
171   * {@code target}.
172   *
173   * @param array the array to search for the sequence {@code target}
174   * @param target the array to search for as a sub-sequence of {@code array}
175   */
176  public static int indexOf(short[] array, short[] target) {
177    checkNotNull(array, "array");
178    checkNotNull(target, "target");
179    if (target.length == 0) {
180      return 0;
181    }
182
183    outer:
184    for (int i = 0; i < array.length - target.length + 1; i++) {
185      for (int j = 0; j < target.length; j++) {
186        if (array[i + j] != target[j]) {
187          continue outer;
188        }
189      }
190      return i;
191    }
192    return -1;
193  }
194
195  /**
196   * Returns the index of the last appearance of the value {@code target} in {@code array}.
197   *
198   * @param array an array of {@code short} values, possibly empty
199   * @param target a primitive {@code short} value
200   * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no
201   *     such index exists.
202   */
203  public static int lastIndexOf(short[] array, short target) {
204    return lastIndexOf(array, target, 0, array.length);
205  }
206
207  // TODO(kevinb): consider making this public
208  private static int lastIndexOf(short[] array, short target, int start, int end) {
209    for (int i = end - 1; i >= start; i--) {
210      if (array[i] == target) {
211        return i;
212      }
213    }
214    return -1;
215  }
216
217  /**
218   * Returns the least value present in {@code array}.
219   *
220   * @param array a <i>nonempty</i> array of {@code short} values
221   * @return the value present in {@code array} that is less than or equal to every other value in
222   *     the array
223   * @throws IllegalArgumentException if {@code array} is empty
224   */
225  public static short min(short... array) {
226    checkArgument(array.length > 0);
227    short min = array[0];
228    for (int i = 1; i < array.length; i++) {
229      if (array[i] < min) {
230        min = array[i];
231      }
232    }
233    return min;
234  }
235
236  /**
237   * Returns the greatest value present in {@code array}.
238   *
239   * @param array a <i>nonempty</i> array of {@code short} values
240   * @return the value present in {@code array} that is greater than or equal to every other value
241   *     in the array
242   * @throws IllegalArgumentException if {@code array} is empty
243   */
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 values from each provided array combined into a single array. For example,
257   * {@code concat(new short[] {a, b}, new short[] {}, new short[] {c}} returns the array
258   * {@code {a, b, c}}.
259   *
260   * @param arrays zero or more {@code short} arrays
261   * @return a single array containing all the values from the source arrays, in order
262   */
263  public static short[] concat(short[]... arrays) {
264    int length = 0;
265    for (short[] array : arrays) {
266      length += array.length;
267    }
268    short[] result = new short[length];
269    int pos = 0;
270    for (short[] array : arrays) {
271      System.arraycopy(array, 0, result, pos, array.length);
272      pos += array.length;
273    }
274    return result;
275  }
276
277  /**
278   * Returns a big-endian representation of {@code value} in a 2-element byte array; equivalent to
279   * {@code ByteBuffer.allocate(2).putShort(value).array()}. For example, the input value {@code
280   * (short) 0x1234} would yield the byte array {@code {0x12, 0x34}}.
281   *
282   * <p>If you need to convert and concatenate several values (possibly even of different types),
283   * use a shared {@link java.nio.ByteBuffer} instance, or use
284   * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer.
285   */
286  @GwtIncompatible // doesn't work
287  public static byte[] toByteArray(short value) {
288    return new byte[] {(byte) (value >> 8), (byte) value};
289  }
290
291  /**
292   * Returns the {@code short} value whose big-endian representation is stored in the first 2 bytes
293   * of {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getShort()}. For example, the
294   * input byte array {@code {0x54, 0x32}} would yield the {@code short} value {@code 0x5432}.
295   *
296   * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more
297   * flexibility at little cost in readability.
298   *
299   * @throws IllegalArgumentException if {@code bytes} has fewer than 2 elements
300   */
301  @GwtIncompatible // doesn't work
302  public static short fromByteArray(byte[] bytes) {
303    checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES);
304    return fromBytes(bytes[0], bytes[1]);
305  }
306
307  /**
308   * Returns the {@code short} value whose byte representation is the given 2 bytes, in big-endian
309   * order; equivalent to {@code Shorts.fromByteArray(new byte[] {b1, b2})}.
310   *
311   * @since 7.0
312   */
313  @GwtIncompatible // doesn't work
314  public static short fromBytes(byte b1, byte b2) {
315    return (short) ((b1 << 8) | (b2 & 0xFF));
316  }
317
318  private static final class ShortConverter extends Converter<String, Short>
319      implements Serializable {
320    static final ShortConverter INSTANCE = new ShortConverter();
321
322    @Override
323    protected Short doForward(String value) {
324      return Short.decode(value);
325    }
326
327    @Override
328    protected String doBackward(Short value) {
329      return value.toString();
330    }
331
332    @Override
333    public String toString() {
334      return "Shorts.stringConverter()";
335    }
336
337    private Object readResolve() {
338      return INSTANCE;
339    }
340
341    private static final long serialVersionUID = 1;
342  }
343
344  /**
345   * Returns a serializable converter object that converts between strings and shorts using
346   * {@link Short#decode} and {@link Short#toString()}. The returned converter throws
347   * {@link NumberFormatException} if the input string is invalid.
348   *
349   * <p><b>Warning:</b> please see {@link Short#decode} to understand exactly how strings are
350   * parsed. For example, the string {@code "0123"} is treated as <i>octal</i> and converted to the
351   * value {@code 83}.
352   *
353   * @since 16.0
354   */
355  @Beta
356  public static Converter<String, Short> stringConverter() {
357    return ShortConverter.INSTANCE;
358  }
359
360  /**
361   * Returns an array containing the same values as {@code array}, but guaranteed to be of a
362   * specified minimum length. If {@code array} already has a length of at least {@code minLength},
363   * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is
364   * returned, containing the values of {@code array}, and zeroes in the remaining places.
365   *
366   * @param array the source array
367   * @param minLength the minimum length the returned array must guarantee
368   * @param padding an extra amount to "grow" the array by if growth is necessary
369   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative
370   * @return an array containing the values of {@code array}, with guaranteed minimum length
371   *     {@code minLength}
372   */
373  public static short[] ensureCapacity(short[] array, int minLength, int padding) {
374    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
375    checkArgument(padding >= 0, "Invalid padding: %s", padding);
376    return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array;
377  }
378
379  /**
380   * Returns a string containing the supplied {@code short} values separated by {@code separator}.
381   * For example, {@code join("-", (short) 1, (short) 2,
382   * (short) 3)} returns the string {@code "1-2-3"}.
383   *
384   * @param separator the text that should appear between consecutive values in the resulting string
385   *     (but not at the start or end)
386   * @param array an array of {@code short} values, possibly empty
387   */
388  public static String join(String separator, short... array) {
389    checkNotNull(separator);
390    if (array.length == 0) {
391      return "";
392    }
393
394    // For pre-sizing a builder, just get the right order of magnitude
395    StringBuilder builder = new StringBuilder(array.length * 6);
396    builder.append(array[0]);
397    for (int i = 1; i < array.length; i++) {
398      builder.append(separator).append(array[i]);
399    }
400    return builder.toString();
401  }
402
403  /**
404   * Returns a comparator that compares two {@code short} arrays <a
405   * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it
406   * compares, using {@link #compare(short, short)}), the first pair of values that follow any
407   * common prefix, or when one array is a prefix of the other, treats the shorter array as the
408   * lesser. For example, {@code [] < [(short) 1] < [(short) 1, (short) 2] < [(short) 2]}.
409   *
410   * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
411   * support only identity equality), but it is consistent with
412   * {@link Arrays#equals(short[], short[])}.
413   *
414   * @since 2.0
415   */
416  public static Comparator<short[]> lexicographicalComparator() {
417    return LexicographicalComparator.INSTANCE;
418  }
419
420  private enum LexicographicalComparator implements Comparator<short[]> {
421    INSTANCE;
422
423    @Override
424    public int compare(short[] left, short[] right) {
425      int minLength = Math.min(left.length, right.length);
426      for (int i = 0; i < minLength; i++) {
427        int result = Shorts.compare(left[i], right[i]);
428        if (result != 0) {
429          return result;
430        }
431      }
432      return left.length - right.length;
433    }
434
435    @Override
436    public String toString() {
437      return "Shorts.lexicographicalComparator()";
438    }
439  }
440
441  /**
442   * Returns an array containing each value of {@code collection}, converted to a {@code short}
443   * value in the manner of {@link Number#shortValue}.
444   *
445   * <p>Elements are copied from the argument collection as if by {@code
446   * collection.toArray()}. Calling this method is as thread-safe as calling that method.
447   *
448   * @param collection a collection of {@code Number} instances
449   * @return an array containing the same values as {@code collection}, in the same order, converted
450   *     to primitives
451   * @throws NullPointerException if {@code collection} or any of its elements is null
452   * @since 1.0 (parameter was {@code Collection<Short>} before 12.0)
453   */
454  public static short[] toArray(Collection<? extends Number> collection) {
455    if (collection instanceof ShortArrayAsList) {
456      return ((ShortArrayAsList) collection).toShortArray();
457    }
458
459    Object[] boxedArray = collection.toArray();
460    int len = boxedArray.length;
461    short[] array = new short[len];
462    for (int i = 0; i < len; i++) {
463      // checkNotNull for GWT (do not optimize)
464      array[i] = ((Number) checkNotNull(boxedArray[i])).shortValue();
465    }
466    return array;
467  }
468
469  /**
470   * Returns a fixed-size list backed by the specified array, similar to
471   * {@link Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any
472   * attempt to set a value to {@code null} will result in a {@link NullPointerException}.
473   *
474   * <p>The returned list maintains the values, but not the identities, of {@code Short} objects
475   * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
476   * the returned list is unspecified.
477   *
478   * @param backingArray the array to back the list
479   * @return a list view of the array
480   */
481  public static List<Short> asList(short... backingArray) {
482    if (backingArray.length == 0) {
483      return Collections.emptyList();
484    }
485    return new ShortArrayAsList(backingArray);
486  }
487
488  @GwtCompatible
489  private static class ShortArrayAsList extends AbstractList<Short>
490      implements RandomAccess, Serializable {
491    final short[] array;
492    final int start;
493    final int end;
494
495    ShortArrayAsList(short[] array) {
496      this(array, 0, array.length);
497    }
498
499    ShortArrayAsList(short[] array, int start, int end) {
500      this.array = array;
501      this.start = start;
502      this.end = end;
503    }
504
505    @Override
506    public int size() {
507      return end - start;
508    }
509
510    @Override
511    public boolean isEmpty() {
512      return false;
513    }
514
515    @Override
516    public Short get(int index) {
517      checkElementIndex(index, size());
518      return array[start + index];
519    }
520
521    @Override
522    public boolean contains(Object target) {
523      // Overridden to prevent a ton of boxing
524      return (target instanceof Short) && Shorts.indexOf(array, (Short) target, start, end) != -1;
525    }
526
527    @Override
528    public int indexOf(Object target) {
529      // Overridden to prevent a ton of boxing
530      if (target instanceof Short) {
531        int i = Shorts.indexOf(array, (Short) target, start, end);
532        if (i >= 0) {
533          return i - start;
534        }
535      }
536      return -1;
537    }
538
539    @Override
540    public int lastIndexOf(Object target) {
541      // Overridden to prevent a ton of boxing
542      if (target instanceof Short) {
543        int i = Shorts.lastIndexOf(array, (Short) target, start, end);
544        if (i >= 0) {
545          return i - start;
546        }
547      }
548      return -1;
549    }
550
551    @Override
552    public Short set(int index, Short element) {
553      checkElementIndex(index, size());
554      short oldValue = array[start + index];
555      // checkNotNull for GWT (do not optimize)
556      array[start + index] = checkNotNull(element);
557      return oldValue;
558    }
559
560    @Override
561    public List<Short> subList(int fromIndex, int toIndex) {
562      int size = size();
563      checkPositionIndexes(fromIndex, toIndex, size);
564      if (fromIndex == toIndex) {
565        return Collections.emptyList();
566      }
567      return new ShortArrayAsList(array, start + fromIndex, start + toIndex);
568    }
569
570    @Override
571    public boolean equals(Object object) {
572      if (object == this) {
573        return true;
574      }
575      if (object instanceof ShortArrayAsList) {
576        ShortArrayAsList that = (ShortArrayAsList) object;
577        int size = size();
578        if (that.size() != size) {
579          return false;
580        }
581        for (int i = 0; i < size; i++) {
582          if (array[start + i] != that.array[that.start + i]) {
583            return false;
584          }
585        }
586        return true;
587      }
588      return super.equals(object);
589    }
590
591    @Override
592    public int hashCode() {
593      int result = 1;
594      for (int i = start; i < end; i++) {
595        result = 31 * result + Shorts.hashCode(array[i]);
596      }
597      return result;
598    }
599
600    @Override
601    public String toString() {
602      StringBuilder builder = new StringBuilder(size() * 6);
603      builder.append('[').append(array[start]);
604      for (int i = start + 1; i < end; i++) {
605        builder.append(", ").append(array[i]);
606      }
607      return builder.append(']').toString();
608    }
609
610    short[] toShortArray() {
611      // Arrays.copyOfRange() is not available under GWT
612      int size = size();
613      short[] result = new short[size];
614      System.arraycopy(array, start, result, 0, size);
615      return result;
616    }
617
618    private static final long serialVersionUID = 0;
619  }
620}