Home | History | Annotate | Download | only in primitives
      1 /*
      2  * Copyright (C) 2008 Google Inc.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  * http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.google.common.primitives;
     18 
     19 import com.google.common.annotations.GwtCompatible;
     20 import com.google.common.annotations.GwtIncompatible;
     21 
     22 import java.io.Serializable;
     23 import java.util.AbstractList;
     24 import java.util.Arrays;
     25 import java.util.Collection;
     26 import java.util.Collections;
     27 import java.util.Comparator;
     28 import java.util.List;
     29 import java.util.RandomAccess;
     30 
     31 import static com.google.common.base.Preconditions.checkArgument;
     32 import static com.google.common.base.Preconditions.checkElementIndex;
     33 import static com.google.common.base.Preconditions.checkNotNull;
     34 import static com.google.common.base.Preconditions.checkPositionIndexes;
     35 
     36 /**
     37  * Static utility methods pertaining to {@code short} primitives, that are not
     38  * already found in either {@link Short} or {@link Arrays}.
     39  *
     40  * @author Kevin Bourrillion
     41  * @since 2009.09.15 <b>tentative</b>
     42  */
     43 @GwtCompatible
     44 public final class Shorts {
     45   private Shorts() {}
     46 
     47   /**
     48    * The number of bytes required to represent a primitive {@code short}
     49    * value.
     50    */
     51   public static final int BYTES = Short.SIZE / Byte.SIZE;
     52 
     53   /**
     54    * Returns a hash code for {@code value}; equal to the result of invoking
     55    * {@code ((Short) value).hashCode()}.
     56    *
     57    * @param value a primitive {@code short} value
     58    * @return a hash code for the value
     59    */
     60   public static int hashCode(short value) {
     61     return value;
     62   }
     63 
     64   /**
     65    * Returns the {@code short} value that is equal to {@code value}, if possible.
     66    *
     67    * @param value any value in the range of the {@code short} type
     68    * @return the {@code short} value that equals {@code value}
     69    * @throws IllegalArgumentException if {@code value} is greater than {@link
     70    *     Short#MAX_VALUE} or less than {@link Short#MIN_VALUE}
     71    */
     72   public static short checkedCast(long value) {
     73     short result = (short) value;
     74     checkArgument(result == value, "Out of range: %s", value);
     75     return result;
     76   }
     77 
     78   /**
     79    * Returns the {@code short} nearest in value to {@code value}.
     80    *
     81    * @param value any {@code long} value
     82    * @return the same value cast to {@code short} if it is in the range of the
     83    *     {@code short} type, {@link Short#MAX_VALUE} if it is too large,
     84    *     or {@link Short#MIN_VALUE} if it is too small
     85    */
     86   public static short saturatedCast(long value) {
     87     if (value > Short.MAX_VALUE) {
     88       return Short.MAX_VALUE;
     89     }
     90     if (value < Short.MIN_VALUE) {
     91       return Short.MIN_VALUE;
     92     }
     93     return (short) value;
     94   }
     95 
     96   /**
     97    * Compares the two specified {@code short} values. The sign of the value
     98    * returned is the same as that of {@code ((Short) a).compareTo(b)}.
     99    *
    100    * @param a the first {@code short} to compare
    101    * @param b the second {@code short} to compare
    102    * @return a negative value if {@code a} is less than {@code b}; a positive
    103    *     value if {@code a} is greater than {@code b}; or zero if they are equal
    104    */
    105   public static int compare(short a, short b) {
    106     return a - b; // safe due to restricted range
    107   }
    108 
    109   /**
    110    * Returns {@code true} if {@code target} is present as an element anywhere in
    111    * {@code array}.
    112    *
    113    * @param array an array of {@code short} values, possibly empty
    114    * @param target a primitive {@code short} value
    115    * @return {@code true} if {@code array[i] == target} for some value of {@code
    116    *     i}
    117    */
    118   public static boolean contains(short[] array, short target) {
    119     for (short value : array) {
    120       if (value == target) {
    121         return true;
    122       }
    123     }
    124     return false;
    125   }
    126 
    127   /**
    128    * Returns the index of the first appearance of the value {@code target} in
    129    * {@code array}.
    130    *
    131    * @param array an array of {@code short} values, possibly empty
    132    * @param target a primitive {@code short} value
    133    * @return the least index {@code i} for which {@code array[i] == target}, or
    134    *     {@code -1} if no such index exists.
    135    */
    136   public static int indexOf(short[] array, short target) {
    137     return indexOf(array, target, 0, array.length);
    138   }
    139 
    140   // TODO: consider making this public
    141   private static int indexOf(
    142       short[] array, short target, int start, int end) {
    143     for (int i = start; i < end; i++) {
    144       if (array[i] == target) {
    145         return i;
    146       }
    147     }
    148     return -1;
    149   }
    150 
    151   /**
    152    * Returns the start position of the first occurrence of the specified {@code
    153    * target} within {@code array}, or {@code -1} if there is no such occurrence.
    154    *
    155    * <p>More formally, returns the lowest index {@code i} such that {@code
    156    * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
    157    * the same elements as {@code target}.
    158    *
    159    * @param array the array to search for the sequence {@code target}
    160    * @param target the array to search for as a sub-sequence of {@code array}
    161    */
    162   public static int indexOf(short[] array, short[] target) {
    163     checkNotNull(array, "array");
    164     checkNotNull(target, "target");
    165     if (target.length == 0) {
    166       return 0;
    167     }
    168 
    169     outer:
    170     for (int i = 0; i < array.length - target.length + 1; i++) {
    171       for (int j = 0; j < target.length; j++) {
    172         if (array[i + j] != target[j]) {
    173           continue outer;
    174         }
    175       }
    176       return i;
    177     }
    178     return -1;
    179   }
    180 
    181   /**
    182    * Returns the index of the last appearance of the value {@code target} in
    183    * {@code array}.
    184    *
    185    * @param array an array of {@code short} values, possibly empty
    186    * @param target a primitive {@code short} value
    187    * @return the greatest index {@code i} for which {@code array[i] == target},
    188    *     or {@code -1} if no such index exists.
    189    */
    190   public static int lastIndexOf(short[] array, short target) {
    191     return lastIndexOf(array, target, 0, array.length);
    192   }
    193 
    194   // TODO: consider making this public
    195   private static int lastIndexOf(
    196       short[] array, short target, int start, int end) {
    197     for (int i = end - 1; i >= start; i--) {
    198       if (array[i] == target) {
    199         return i;
    200       }
    201     }
    202     return -1;
    203   }
    204 
    205   /**
    206    * Returns the least value present in {@code array}.
    207    *
    208    * @param array a <i>nonempty</i> array of {@code short} values
    209    * @return the value present in {@code array} that is less than or equal to
    210    *     every other value in the array
    211    * @throws IllegalArgumentException if {@code array} is empty
    212    */
    213   public static short min(short... array) {
    214     checkArgument(array.length > 0);
    215     short min = array[0];
    216     for (int i = 1; i < array.length; i++) {
    217       if (array[i] < min) {
    218         min = array[i];
    219       }
    220     }
    221     return min;
    222   }
    223 
    224   /**
    225    * Returns the greatest value present in {@code array}.
    226    *
    227    * @param array a <i>nonempty</i> array of {@code short} values
    228    * @return the value present in {@code array} that is greater than or equal to
    229    *     every other value in the array
    230    * @throws IllegalArgumentException if {@code array} is empty
    231    */
    232   public static short max(short... array) {
    233     checkArgument(array.length > 0);
    234     short max = array[0];
    235     for (int i = 1; i < array.length; i++) {
    236       if (array[i] > max) {
    237         max = array[i];
    238       }
    239     }
    240     return max;
    241   }
    242 
    243   /**
    244    * Returns the values from each provided array combined into a single array.
    245    * For example, {@code concat(new short[] {a, b}, new short[] {}, new
    246    * short[] {c}} returns the array {@code {a, b, c}}.
    247    *
    248    * @param arrays zero or more {@code short} arrays
    249    * @return a single array containing all the values from the source arrays, in
    250    *     order
    251    */
    252   public static short[] concat(short[]... arrays) {
    253     int length = 0;
    254     for (short[] array : arrays) {
    255       length += array.length;
    256     }
    257     short[] result = new short[length];
    258     int pos = 0;
    259     for (short[] array : arrays) {
    260       System.arraycopy(array, 0, result, pos, array.length);
    261       pos += array.length;
    262     }
    263     return result;
    264   }
    265 
    266   /**
    267    * Returns a big-endian representation of {@code value} in a ?-element byte
    268    * array; equivalent to {@code
    269    * ByteBuffer.allocate(?).putShort(value).array()}.  For example, the input
    270    * value {@code ?} would yield the byte array {@code {?}}.
    271    *
    272    * <p>If you need to convert and concatenate several values (possibly even of
    273    * different types), use a shared {@link java.nio.ByteBuffer} instance, or use
    274    * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable
    275    * buffer.
    276    */
    277   @GwtIncompatible("doesn't work")
    278   public static byte[] toByteArray(short value) {
    279     return new byte[] {
    280         (byte) (value >> 8),
    281         (byte) value};
    282   }
    283 
    284   /**
    285    * Returns the {@code short} value whose big-endian representation is
    286    * stored in the first ? bytes of {@code bytes}; equivalent to {@code
    287    * ByteBuffer.wrap(bytes).getShort()}. For example, the input byte array
    288    * {@code {?}} would yield the {@code short} value {@code ?}.
    289    *
    290    * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that
    291    * library exposes much more flexibility at little cost in readability.
    292    *
    293    * @throws IllegalArgumentException if {@code bytes} has fewer than ?
    294    *     elements
    295    */
    296   @GwtIncompatible("doesn't work")
    297   public static short fromByteArray(byte[] bytes) {
    298     checkArgument(bytes.length >= BYTES,
    299         "array too small: %s < %s", bytes.length, BYTES);
    300     return (short) ((bytes[0] << 8) | (bytes[1] & 0xFF));
    301   }
    302 
    303   /**
    304    * Returns an array containing the same values as {@code array}, but
    305    * guaranteed to be of a specified minimum length. If {@code array} already
    306    * has a length of at least {@code minLength}, it is returned directly.
    307    * Otherwise, a new array of size {@code minLength + padding} is returned,
    308    * containing the values of {@code array}, and zeroes in the remaining places.
    309    *
    310    * @param array the source array
    311    * @param minLength the minimum length the returned array must guarantee
    312    * @param padding an extra amount to "grow" the array by if growth is
    313    *     necessary
    314    * @throws IllegalArgumentException if {@code minLength} or {@code padding} is
    315    *     negative
    316    * @return an array containing the values of {@code array}, with guaranteed
    317    *     minimum length {@code minLength}
    318    */
    319   public static short[] ensureCapacity(
    320       short[] array, int minLength, int padding) {
    321     checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
    322     checkArgument(padding >= 0, "Invalid padding: %s", padding);
    323     return (array.length < minLength)
    324         ? copyOf(array, minLength + padding)
    325         : array;
    326   }
    327 
    328   // Arrays.copyOf() requires Java 6
    329   private static short[] copyOf(short[] original, int length) {
    330     short[] copy = new short[length];
    331     System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
    332     return copy;
    333   }
    334 
    335   /**
    336    * Returns a string containing the supplied {@code short} values separated
    337    * by {@code separator}. For example, {@code join("-", 1?, 2?, 3?)} returns
    338    * the string {@code "1-2-3"}.
    339    *
    340    * @param separator the text that should appear between consecutive values in
    341    *     the resulting string (but not at the start or end)
    342    * @param array an array of {@code short} values, possibly empty
    343    */
    344   public static String join(String separator, short... array) {
    345     checkNotNull(separator);
    346     if (array.length == 0) {
    347       return "";
    348     }
    349 
    350     // For pre-sizing a builder, just get the right order of magnitude
    351     StringBuilder builder = new StringBuilder(array.length * 6);
    352     builder.append(array[0]);
    353     for (int i = 1; i < array.length; i++) {
    354       builder.append(separator).append(array[i]);
    355     }
    356     return builder.toString();
    357   }
    358 
    359   /**
    360    * Returns a comparator that compares two {@code short} arrays
    361    * lexicographically. That is, it compares, using {@link
    362    * #compare(short, short)}), the first pair of values that follow any
    363    * common prefix, or when one array is a prefix of the other, treats the
    364    * shorter array as the lesser. For example, {@code [] < [(short) 1] <
    365    * [(short) 1, (short) 2] < [(short) 2]}.
    366    *
    367    * <p>The returned comparator is inconsistent with {@link
    368    * Object#equals(Object)} (since arrays support only identity equality), but
    369    * it is consistent with {@link Arrays#equals(short[], short[])}.
    370    *
    371    * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
    372    *     Lexicographical order</a> article at Wikipedia
    373    * @since 2010.01.04 <b>tentative</b>
    374    */
    375   public static Comparator<short[]> lexicographicalComparator() {
    376     return LexicographicalComparator.INSTANCE;
    377   }
    378 
    379   private enum LexicographicalComparator implements Comparator<short[]> {
    380     INSTANCE;
    381 
    382     public int compare(short[] left, short[] right) {
    383       int minLength = Math.min(left.length, right.length);
    384       for (int i = 0; i < minLength; i++) {
    385         int result = Shorts.compare(left[i], right[i]);
    386         if (result != 0) {
    387           return result;
    388         }
    389       }
    390       return left.length - right.length;
    391     }
    392   }
    393 
    394   /**
    395    * Copies a collection of {@code Short} instances into a new array of
    396    * primitive {@code short} values.
    397    *
    398    * <p>Elements are copied from the argument collection as if by {@code
    399    * collection.toArray()}.  Calling this method is as thread-safe as calling
    400    * that method.
    401    *
    402    * @param collection a collection of {@code Short} objects
    403    * @return an array containing the same values as {@code collection}, in the
    404    *     same order, converted to primitives
    405    * @throws NullPointerException if {@code collection} or any of its elements
    406    *     is null
    407    */
    408   public static short[] toArray(Collection<Short> collection) {
    409     if (collection instanceof ShortArrayAsList) {
    410       return ((ShortArrayAsList) collection).toShortArray();
    411     }
    412 
    413     Object[] boxedArray = collection.toArray();
    414     int len = boxedArray.length;
    415     short[] array = new short[len];
    416     for (int i = 0; i < len; i++) {
    417       array[i] = (Short) boxedArray[i];
    418     }
    419     return array;
    420   }
    421 
    422   /**
    423    * Returns a fixed-size list backed by the specified array, similar to {@link
    424    * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
    425    * but any attempt to set a value to {@code null} will result in a {@link
    426    * NullPointerException}.
    427    *
    428    * <p>The returned list maintains the values, but not the identities, of
    429    * {@code Short} objects written to or read from it.  For example, whether
    430    * {@code list.get(0) == list.get(0)} is true for the returned list is
    431    * unspecified.
    432    *
    433    * @param backingArray the array to back the list
    434    * @return a list view of the array
    435    */
    436   public static List<Short> asList(short... backingArray) {
    437     if (backingArray.length == 0) {
    438       return Collections.emptyList();
    439     }
    440     return new ShortArrayAsList(backingArray);
    441   }
    442 
    443   @GwtCompatible
    444   private static class ShortArrayAsList extends AbstractList<Short>
    445       implements RandomAccess, Serializable {
    446     final short[] array;
    447     final int start;
    448     final int end;
    449 
    450     ShortArrayAsList(short[] array) {
    451       this(array, 0, array.length);
    452     }
    453 
    454     ShortArrayAsList(short[] array, int start, int end) {
    455       this.array = array;
    456       this.start = start;
    457       this.end = end;
    458     }
    459 
    460     @Override public int size() {
    461       return end - start;
    462     }
    463 
    464     @Override public boolean isEmpty() {
    465       return false;
    466     }
    467 
    468     @Override public Short get(int index) {
    469       checkElementIndex(index, size());
    470       return array[start + index];
    471     }
    472 
    473     @Override public boolean contains(Object target) {
    474       // Overridden to prevent a ton of boxing
    475       return (target instanceof Short)
    476           && Shorts.indexOf(array, (Short) target, start, end) != -1;
    477     }
    478 
    479     @Override public int indexOf(Object target) {
    480       // Overridden to prevent a ton of boxing
    481       if (target instanceof Short) {
    482         int i = Shorts.indexOf(array, (Short) target, start, end);
    483         if (i >= 0) {
    484           return i - start;
    485         }
    486       }
    487       return -1;
    488     }
    489 
    490     @Override public int lastIndexOf(Object target) {
    491       // Overridden to prevent a ton of boxing
    492       if (target instanceof Short) {
    493         int i = Shorts.lastIndexOf(array, (Short) target, start, end);
    494         if (i >= 0) {
    495           return i - start;
    496         }
    497       }
    498       return -1;
    499     }
    500 
    501     @Override public Short set(int index, Short element) {
    502       checkElementIndex(index, size());
    503       short oldValue = array[start + index];
    504       array[start + index] = element;
    505       return oldValue;
    506     }
    507 
    508     /** In GWT, List and AbstractList do not have the subList method. */
    509     /*@Override*/ public List<Short> subList(int fromIndex, int toIndex) {
    510       int size = size();
    511       checkPositionIndexes(fromIndex, toIndex, size);
    512       if (fromIndex == toIndex) {
    513         return Collections.emptyList();
    514       }
    515       return new ShortArrayAsList(array, start + fromIndex, start + toIndex);
    516     }
    517 
    518     @Override public boolean equals(Object object) {
    519       if (object == this) {
    520         return true;
    521       }
    522       if (object instanceof ShortArrayAsList) {
    523         ShortArrayAsList that = (ShortArrayAsList) object;
    524         int size = size();
    525         if (that.size() != size) {
    526           return false;
    527         }
    528         for (int i = 0; i < size; i++) {
    529           if (array[start + i] != that.array[that.start + i]) {
    530             return false;
    531           }
    532         }
    533         return true;
    534       }
    535       return super.equals(object);
    536     }
    537 
    538     @Override public int hashCode() {
    539       int result = 1;
    540       for (int i = start; i < end; i++) {
    541         result = 31 * result + Shorts.hashCode(array[i]);
    542       }
    543       return result;
    544     }
    545 
    546     @Override public String toString() {
    547       StringBuilder builder = new StringBuilder(size() * 6);
    548       builder.append('[').append(array[start]);
    549       for (int i = start + 1; i < end; i++) {
    550         builder.append(", ").append(array[i]);
    551       }
    552       return builder.append(']').toString();
    553     }
    554 
    555     short[] toShortArray() {
    556       // Arrays.copyOfRange() requires Java 6
    557       int size = size();
    558       short[] result = new short[size];
    559       System.arraycopy(array, start, result, 0, size);
    560       return result;
    561     }
    562 
    563     private static final long serialVersionUID = 0;
    564   }
    565 }
    566