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   * Returns an array containing each value of {@code collection}, converted to a {@code short}
459   * value in the manner of {@link Number#shortValue}.
460   *
461   * <p>Elements are copied from the argument collection as if by {@code
462   * collection.toArray()}. Calling this method is as thread-safe as calling that method.
463   *
464   * @param collection a collection of {@code Number} instances
465   * @return an array containing the same values as {@code collection}, in the same order, converted
466   *     to primitives
467   * @throws NullPointerException if {@code collection} or any of its elements is null
468   * @since 1.0 (parameter was {@code Collection<Short>} before 12.0)
469   */
470  public static short[] toArray(Collection<? extends Number> collection) {
471    if (collection instanceof ShortArrayAsList) {
472      return ((ShortArrayAsList) collection).toShortArray();
473    }
474
475    Object[] boxedArray = collection.toArray();
476    int len = boxedArray.length;
477    short[] array = new short[len];
478    for (int i = 0; i < len; i++) {
479      // checkNotNull for GWT (do not optimize)
480      array[i] = ((Number) checkNotNull(boxedArray[i])).shortValue();
481    }
482    return array;
483  }
484
485  /**
486   * Returns a fixed-size list backed by the specified array, similar to
487   * {@link Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any
488   * attempt to set a value to {@code null} will result in a {@link NullPointerException}.
489   *
490   * <p>The returned list maintains the values, but not the identities, of {@code Short} objects
491   * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
492   * the returned list is unspecified.
493   *
494   * @param backingArray the array to back the list
495   * @return a list view of the array
496   */
497  public static List<Short> asList(short... backingArray) {
498    if (backingArray.length == 0) {
499      return Collections.emptyList();
500    }
501    return new ShortArrayAsList(backingArray);
502  }
503
504  @GwtCompatible
505  private static class ShortArrayAsList extends AbstractList<Short>
506      implements RandomAccess, Serializable {
507    final short[] array;
508    final int start;
509    final int end;
510
511    ShortArrayAsList(short[] array) {
512      this(array, 0, array.length);
513    }
514
515    ShortArrayAsList(short[] array, int start, int end) {
516      this.array = array;
517      this.start = start;
518      this.end = end;
519    }
520
521    @Override
522    public int size() {
523      return end - start;
524    }
525
526    @Override
527    public boolean isEmpty() {
528      return false;
529    }
530
531    @Override
532    public Short get(int index) {
533      checkElementIndex(index, size());
534      return array[start + index];
535    }
536
537    @Override
538    public boolean contains(Object target) {
539      // Overridden to prevent a ton of boxing
540      return (target instanceof Short) && Shorts.indexOf(array, (Short) target, start, end) != -1;
541    }
542
543    @Override
544    public int indexOf(Object target) {
545      // Overridden to prevent a ton of boxing
546      if (target instanceof Short) {
547        int i = Shorts.indexOf(array, (Short) target, start, end);
548        if (i >= 0) {
549          return i - start;
550        }
551      }
552      return -1;
553    }
554
555    @Override
556    public int lastIndexOf(Object target) {
557      // Overridden to prevent a ton of boxing
558      if (target instanceof Short) {
559        int i = Shorts.lastIndexOf(array, (Short) target, start, end);
560        if (i >= 0) {
561          return i - start;
562        }
563      }
564      return -1;
565    }
566
567    @Override
568    public Short set(int index, Short element) {
569      checkElementIndex(index, size());
570      short oldValue = array[start + index];
571      // checkNotNull for GWT (do not optimize)
572      array[start + index] = checkNotNull(element);
573      return oldValue;
574    }
575
576    @Override
577    public List<Short> subList(int fromIndex, int toIndex) {
578      int size = size();
579      checkPositionIndexes(fromIndex, toIndex, size);
580      if (fromIndex == toIndex) {
581        return Collections.emptyList();
582      }
583      return new ShortArrayAsList(array, start + fromIndex, start + toIndex);
584    }
585
586    @Override
587    public boolean equals(Object object) {
588      if (object == this) {
589        return true;
590      }
591      if (object instanceof ShortArrayAsList) {
592        ShortArrayAsList that = (ShortArrayAsList) object;
593        int size = size();
594        if (that.size() != size) {
595          return false;
596        }
597        for (int i = 0; i < size; i++) {
598          if (array[start + i] != that.array[that.start + i]) {
599            return false;
600          }
601        }
602        return true;
603      }
604      return super.equals(object);
605    }
606
607    @Override
608    public int hashCode() {
609      int result = 1;
610      for (int i = start; i < end; i++) {
611        result = 31 * result + Shorts.hashCode(array[i]);
612      }
613      return result;
614    }
615
616    @Override
617    public String toString() {
618      StringBuilder builder = new StringBuilder(size() * 6);
619      builder.append('[').append(array[start]);
620      for (int i = start + 1; i < end; i++) {
621        builder.append(", ").append(array[i]);
622      }
623      return builder.append(']').toString();
624    }
625
626    short[] toShortArray() {
627      return Arrays.copyOfRange(array, start, end);
628    }
629
630    private static final long serialVersionUID = 0;
631  }
632}