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