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