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