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 char} primitives, that are not
     38  * already found in either {@link Character} or {@link Arrays}.
     39  *
     40  * @author Kevin Bourrillion
     41  * @since 2009.09.15 <b>tentative</b>
     42  */
     43 @GwtCompatible
     44 public final class Chars {
     45   private Chars() {}
     46 
     47   /**
     48    * The number of bytes required to represent a primitive {@code char}
     49    * value.
     50    */
     51   public static final int BYTES = Character.SIZE / Byte.SIZE;
     52 
     53   /**
     54    * Returns a hash code for {@code value}; equal to the result of invoking
     55    * {@code ((Character) value).hashCode()}.
     56    *
     57    * @param value a primitive {@code char} value
     58    * @return a hash code for the value
     59    */
     60   public static int hashCode(char value) {
     61     return value;
     62   }
     63 
     64   /**
     65    * Returns the {@code char} value that is equal to {@code value}, if possible.
     66    *
     67    * @param value any value in the range of the {@code char} type
     68    * @return the {@code char} value that equals {@code value}
     69    * @throws IllegalArgumentException if {@code value} is greater than {@link
     70    *     Character#MAX_VALUE} or less than {@link Character#MIN_VALUE}
     71    */
     72   public static char checkedCast(long value) {
     73     char result = (char) value;
     74     checkArgument(result == value, "Out of range: %s", value);
     75     return result;
     76   }
     77 
     78   /**
     79    * Returns the {@code char} nearest in value to {@code value}.
     80    *
     81    * @param value any {@code long} value
     82    * @return the same value cast to {@code char} if it is in the range of the
     83    *     {@code char} type, {@link Character#MAX_VALUE} if it is too large,
     84    *     or {@link Character#MIN_VALUE} if it is too small
     85    */
     86   public static char saturatedCast(long value) {
     87     if (value > Character.MAX_VALUE) {
     88       return Character.MAX_VALUE;
     89     }
     90     if (value < Character.MIN_VALUE) {
     91       return Character.MIN_VALUE;
     92     }
     93     return (char) value;
     94   }
     95 
     96   /**
     97    * Compares the two specified {@code char} values. The sign of the value
     98    * returned is the same as that of {@code ((Character) a).compareTo(b)}.
     99    *
    100    * @param a the first {@code char} to compare
    101    * @param b the second {@code char} 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(char a, char 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 char} values, possibly empty
    114    * @param target a primitive {@code char} value
    115    * @return {@code true} if {@code array[i] == target} for some value of {@code
    116    *     i}
    117    */
    118   public static boolean contains(char[] array, char target) {
    119     for (char 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 char} values, possibly empty
    132    * @param target a primitive {@code char} 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(char[] array, char target) {
    137     return indexOf(array, target, 0, array.length);
    138   }
    139 
    140   // TODO: consider making this public
    141   private static int indexOf(
    142       char[] array, char 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(char[] array, char[] 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 char} values, possibly empty
    186    * @param target a primitive {@code char} 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(char[] array, char target) {
    191     return lastIndexOf(array, target, 0, array.length);
    192   }
    193 
    194   // TODO: consider making this public
    195   private static int lastIndexOf(
    196       char[] array, char 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 char} 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 char min(char... array) {
    214     checkArgument(array.length > 0);
    215     char 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 char} 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 char max(char... array) {
    233     checkArgument(array.length > 0);
    234     char 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 char[] {a, b}, new char[] {}, new
    246    * char[] {c}} returns the array {@code {a, b, c}}.
    247    *
    248    * @param arrays zero or more {@code char} arrays
    249    * @return a single array containing all the values from the source arrays, in
    250    *     order
    251    */
    252   public static char[] concat(char[]... arrays) {
    253     int length = 0;
    254     for (char[] array : arrays) {
    255       length += array.length;
    256     }
    257     char[] result = new char[length];
    258     int pos = 0;
    259     for (char[] 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 2-element byte
    268    * array; equivalent to {@code
    269    * ByteBuffer.allocate(2).putChar(value).array()}.  For example, the input
    270    * value {@code '\\u5432'} would yield the byte array {@code {0x54, 0x32}}.
    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(char value) {
    279     return new byte[] {
    280         (byte) (value >> 8),
    281         (byte) value};
    282   }
    283 
    284   /**
    285    * Returns the {@code char} value whose big-endian representation is
    286    * stored in the first 2 bytes of {@code bytes}; equivalent to {@code
    287    * ByteBuffer.wrap(bytes).getChar()}. For example, the input byte array
    288    * {@code {0x54, 0x32}} would yield the {@code char} value {@code '\\u5432'}.
    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 2
    294    *     elements
    295    */
    296   @GwtIncompatible("doesn't work")
    297   public static char fromByteArray(byte[] bytes) {
    298     checkArgument(bytes.length >= BYTES,
    299         "array too small: %s < %s", bytes.length, BYTES);
    300     return (char) ((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 char[] ensureCapacity(
    320       char[] 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 char[] copyOf(char[] original, int length) {
    330     char[] copy = new char[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 char} 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 char} values, possibly empty
    343    */
    344   public static String join(String separator, char... array) {
    345     checkNotNull(separator);
    346     int len = array.length;
    347     if (len == 0) {
    348       return "";
    349     }
    350 
    351     StringBuilder builder
    352         = new StringBuilder(len + separator.length() * (len - 1));
    353     builder.append(array[0]);
    354     for (int i = 1; i < len; i++) {
    355       builder.append(separator).append(array[i]);
    356     }
    357     return builder.toString();
    358   }
    359 
    360   /**
    361    * Returns a comparator that compares two {@code char} arrays
    362    * lexicographically. That is, it compares, using {@link
    363    * #compare(char, char)}), the first pair of values that follow any
    364    * common prefix, or when one array is a prefix of the other, treats the
    365    * shorter array as the lesser. For example,
    366    * {@code [] < ['a'] < ['a', 'b'] < ['b']}.
    367    *
    368    * <p>The returned comparator is inconsistent with {@link
    369    * Object#equals(Object)} (since arrays support only identity equality), but
    370    * it is consistent with {@link Arrays#equals(char[], char[])}.
    371    *
    372    * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
    373    *     Lexicographical order</a> article at Wikipedia
    374    * @since 2010.01.04 <b>tentative</b>
    375    */
    376   public static Comparator<char[]> lexicographicalComparator() {
    377     return LexicographicalComparator.INSTANCE;
    378   }
    379 
    380   private enum LexicographicalComparator implements Comparator<char[]> {
    381     INSTANCE;
    382 
    383     public int compare(char[] left, char[] right) {
    384       int minLength = Math.min(left.length, right.length);
    385       for (int i = 0; i < minLength; i++) {
    386         int result = Chars.compare(left[i], right[i]);
    387         if (result != 0) {
    388           return result;
    389         }
    390       }
    391       return left.length - right.length;
    392     }
    393   }
    394 
    395   /**
    396    * Copies a collection of {@code Character} instances into a new array of
    397    * primitive {@code char} values.
    398    *
    399    * <p>Elements are copied from the argument collection as if by {@code
    400    * collection.toArray()}.  Calling this method is as thread-safe as calling
    401    * that method.
    402    *
    403    * @param collection a collection of {@code Character} objects
    404    * @return an array containing the same values as {@code collection}, in the
    405    *     same order, converted to primitives
    406    * @throws NullPointerException if {@code collection} or any of its elements
    407    *     is null
    408    */
    409   public static char[] toArray(Collection<Character> collection) {
    410     if (collection instanceof CharArrayAsList) {
    411       return ((CharArrayAsList) collection).toCharArray();
    412     }
    413 
    414     Object[] boxedArray = collection.toArray();
    415     int len = boxedArray.length;
    416     char[] array = new char[len];
    417     for (int i = 0; i < len; i++) {
    418       array[i] = (Character) boxedArray[i];
    419     }
    420     return array;
    421   }
    422 
    423   /**
    424    * Returns a fixed-size list backed by the specified array, similar to {@link
    425    * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
    426    * but any attempt to set a value to {@code null} will result in a {@link
    427    * NullPointerException}.
    428    *
    429    * <p>The returned list maintains the values, but not the identities, of
    430    * {@code Character} objects written to or read from it.  For example, whether
    431    * {@code list.get(0) == list.get(0)} is true for the returned list is
    432    * unspecified.
    433    *
    434    * @param backingArray the array to back the list
    435    * @return a list view of the array
    436    */
    437   public static List<Character> asList(char... backingArray) {
    438     if (backingArray.length == 0) {
    439       return Collections.emptyList();
    440     }
    441     return new CharArrayAsList(backingArray);
    442   }
    443 
    444   @GwtCompatible
    445   private static class CharArrayAsList extends AbstractList<Character>
    446       implements RandomAccess, Serializable {
    447     final char[] array;
    448     final int start;
    449     final int end;
    450 
    451     CharArrayAsList(char[] array) {
    452       this(array, 0, array.length);
    453     }
    454 
    455     CharArrayAsList(char[] array, int start, int end) {
    456       this.array = array;
    457       this.start = start;
    458       this.end = end;
    459     }
    460 
    461     @Override public int size() {
    462       return end - start;
    463     }
    464 
    465     @Override public boolean isEmpty() {
    466       return false;
    467     }
    468 
    469     @Override public Character get(int index) {
    470       checkElementIndex(index, size());
    471       return array[start + index];
    472     }
    473 
    474     @Override public boolean contains(Object target) {
    475       // Overridden to prevent a ton of boxing
    476       return (target instanceof Character)
    477           && Chars.indexOf(array, (Character) target, start, end) != -1;
    478     }
    479 
    480     @Override public int indexOf(Object target) {
    481       // Overridden to prevent a ton of boxing
    482       if (target instanceof Character) {
    483         int i = Chars.indexOf(array, (Character) target, start, end);
    484         if (i >= 0) {
    485           return i - start;
    486         }
    487       }
    488       return -1;
    489     }
    490 
    491     @Override public int lastIndexOf(Object target) {
    492       // Overridden to prevent a ton of boxing
    493       if (target instanceof Character) {
    494         int i = Chars.lastIndexOf(array, (Character) target, start, end);
    495         if (i >= 0) {
    496           return i - start;
    497         }
    498       }
    499       return -1;
    500     }
    501 
    502     @Override public Character set(int index, Character element) {
    503       checkElementIndex(index, size());
    504       char oldValue = array[start + index];
    505       array[start + index] = element;
    506       return oldValue;
    507     }
    508 
    509     /** In GWT, List and AbstractList do not have the subList method. */
    510     /*@Override*/ public List<Character> subList(int fromIndex, int toIndex) {
    511       int size = size();
    512       checkPositionIndexes(fromIndex, toIndex, size);
    513       if (fromIndex == toIndex) {
    514         return Collections.emptyList();
    515       }
    516       return new CharArrayAsList(array, start + fromIndex, start + toIndex);
    517     }
    518 
    519     @Override public boolean equals(Object object) {
    520       if (object == this) {
    521         return true;
    522       }
    523       if (object instanceof CharArrayAsList) {
    524         CharArrayAsList that = (CharArrayAsList) object;
    525         int size = size();
    526         if (that.size() != size) {
    527           return false;
    528         }
    529         for (int i = 0; i < size; i++) {
    530           if (array[start + i] != that.array[that.start + i]) {
    531             return false;
    532           }
    533         }
    534         return true;
    535       }
    536       return super.equals(object);
    537     }
    538 
    539     @Override public int hashCode() {
    540       int result = 1;
    541       for (int i = start; i < end; i++) {
    542         result = 31 * result + Chars.hashCode(array[i]);
    543       }
    544       return result;
    545     }
    546 
    547     @Override public String toString() {
    548       StringBuilder builder = new StringBuilder(size() * 3);
    549       builder.append('[').append(array[start]);
    550       for (int i = start + 1; i < end; i++) {
    551         builder.append(", ").append(array[i]);
    552       }
    553       return builder.append(']').toString();
    554     }
    555 
    556     char[] toCharArray() {
    557       // Arrays.copyOfRange() requires Java 6
    558       int size = size();
    559       char[] result = new char[size];
    560       System.arraycopy(array, start, result, 0, size);
    561       return result;
    562     }
    563 
    564     private static final long serialVersionUID = 0;
    565   }
    566 }
    567