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.GwtCompatible;
023import com.google.common.annotations.GwtIncompatible;
024import com.google.errorprone.annotations.InlineMe;
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.CheckForNull;
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 <a
043 * 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)
049@ElementTypesAreNonnullByDefault
050public final class Chars {
051  private Chars() {}
052
053  /**
054   * The number of bytes required to represent a primitive {@code char} value.
055   *
056   * <p><b>Java 8+ users:</b> use {@link Character#BYTES} instead.
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 {@code ((Character)
062   * value).hashCode()}.
063   *
064   * <p><b>Java 8+ users:</b> use {@link Character#hashCode(char)} instead.
065   *
066   * @param value a primitive {@code char} value
067   * @return a hash code for the value
068   */
069  public static int hashCode(char value) {
070    return value;
071  }
072
073  /**
074   * Returns the {@code char} value that is equal to {@code value}, if possible.
075   *
076   * @param value any value in the range of the {@code char} type
077   * @return the {@code char} value that equals {@code value}
078   * @throws IllegalArgumentException if {@code value} is greater than {@link Character#MAX_VALUE}
079   *     or less than {@link Character#MIN_VALUE}
080   */
081  public static char checkedCast(long value) {
082    char result = (char) value;
083    checkArgument(result == value, "Out of range: %s", value);
084    return result;
085  }
086
087  /**
088   * Returns the {@code char} nearest in value to {@code value}.
089   *
090   * @param value any {@code long} value
091   * @return the same value cast to {@code char} if it is in the range of the {@code char} type,
092   *     {@link Character#MAX_VALUE} if it is too large, or {@link Character#MIN_VALUE} if it is too
093   *     small
094   */
095  public static char saturatedCast(long value) {
096    if (value > Character.MAX_VALUE) {
097      return Character.MAX_VALUE;
098    }
099    if (value < Character.MIN_VALUE) {
100      return Character.MIN_VALUE;
101    }
102    return (char) value;
103  }
104
105  /**
106   * Compares the two specified {@code char} values. The sign of the value returned is the same as
107   * that of {@code ((Character) a).compareTo(b)}.
108   *
109   * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated; use the
110   * equivalent {@link Character#compare} method instead.
111   *
112   * @param a the first {@code char} to compare
113   * @param b the second {@code char} to compare
114   * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is
115   *     greater than {@code b}; or zero if they are equal
116   */
117  @InlineMe(replacement = "Character.compare(a, b)")
118  public static int compare(char a, char b) {
119    return Character.compare(a, b);
120  }
121
122  /**
123   * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}.
124   *
125   * @param array an array of {@code char} values, possibly empty
126   * @param target a primitive {@code char} value
127   * @return {@code true} if {@code array[i] == target} for some value of {@code i}
128   */
129  public static boolean contains(char[] array, char target) {
130    for (char value : array) {
131      if (value == target) {
132        return true;
133      }
134    }
135    return false;
136  }
137
138  /**
139   * Returns the index of the first appearance of the value {@code target} in {@code array}.
140   *
141   * @param array an array of {@code char} values, possibly empty
142   * @param target a primitive {@code char} value
143   * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no
144   *     such index exists.
145   */
146  public static int indexOf(char[] array, char target) {
147    return indexOf(array, target, 0, array.length);
148  }
149
150  // TODO(kevinb): consider making this public
151  private static int indexOf(char[] array, char target, int start, int end) {
152    for (int i = start; i < end; i++) {
153      if (array[i] == target) {
154        return i;
155      }
156    }
157    return -1;
158  }
159
160  /**
161   * Returns the start position of the first occurrence of the specified {@code target} within
162   * {@code array}, or {@code -1} if there is no such occurrence.
163   *
164   * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array,
165   * i, i + target.length)} contains exactly the same elements as {@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 {@code
254   * 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  public static char constrainToRange(char value, char min, char max) {
263    checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max);
264    return value < min ? min : value < max ? value : max;
265  }
266
267  /**
268   * Returns the values from each provided array combined into a single array. For example, {@code
269   * concat(new char[] {a, b}, new char[] {}, new char[] {c}} returns the array {@code {a, b, c}}.
270   *
271   * @param arrays zero or more {@code char} arrays
272   * @return a single array containing all the values from the source arrays, in order
273   */
274  public static char[] concat(char[]... arrays) {
275    int length = 0;
276    for (char[] array : arrays) {
277      length += array.length;
278    }
279    char[] result = new char[length];
280    int pos = 0;
281    for (char[] array : arrays) {
282      System.arraycopy(array, 0, result, pos, array.length);
283      pos += array.length;
284    }
285    return result;
286  }
287
288  /**
289   * Returns a big-endian representation of {@code value} in a 2-element byte array; equivalent to
290   * {@code ByteBuffer.allocate(2).putChar(value).array()}. For example, the input value {@code
291   * '\\u5432'} would yield the byte array {@code {0x54, 0x32}}.
292   *
293   * <p>If you need to convert and concatenate several values (possibly even of different types),
294   * use a shared {@link java.nio.ByteBuffer} instance, or use {@link
295   * com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer.
296   */
297  @GwtIncompatible // doesn't work
298  public static byte[] toByteArray(char value) {
299    return new byte[] {(byte) (value >> 8), (byte) value};
300  }
301
302  /**
303   * Returns the {@code char} value whose big-endian representation is stored in the first 2 bytes
304   * of {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getChar()}. For example, the
305   * input byte array {@code {0x54, 0x32}} would yield the {@code char} value {@code '\\u5432'}.
306   *
307   * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more
308   * flexibility at little cost in readability.
309   *
310   * @throws IllegalArgumentException if {@code bytes} has fewer than 2 elements
311   */
312  @GwtIncompatible // doesn't work
313  public static char fromByteArray(byte[] bytes) {
314    checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES);
315    return fromBytes(bytes[0], bytes[1]);
316  }
317
318  /**
319   * Returns the {@code char} value whose byte representation is the given 2 bytes, in big-endian
320   * order; equivalent to {@code Chars.fromByteArray(new byte[] {b1, b2})}.
321   *
322   * @since 7.0
323   */
324  @GwtIncompatible // doesn't work
325  public static char fromBytes(byte b1, byte b2) {
326    return (char) ((b1 << 8) | (b2 & 0xFF));
327  }
328
329  /**
330   * Returns an array containing the same values as {@code array}, but guaranteed to be of a
331   * specified minimum length. If {@code array} already has a length of at least {@code minLength},
332   * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is
333   * returned, containing the values of {@code array}, and zeroes in the remaining places.
334   *
335   * @param array the source array
336   * @param minLength the minimum length the returned array must guarantee
337   * @param padding an extra amount to "grow" the array by if growth is necessary
338   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative
339   * @return an array containing the values of {@code array}, with guaranteed minimum length {@code
340   *     minLength}
341   */
342  public static char[] ensureCapacity(char[] array, int minLength, int padding) {
343    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
344    checkArgument(padding >= 0, "Invalid padding: %s", padding);
345    return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array;
346  }
347
348  /**
349   * Returns a string containing the supplied {@code char} values separated by {@code separator}.
350   * For example, {@code join("-", '1', '2', '3')} returns the string {@code "1-2-3"}.
351   *
352   * @param separator the text that should appear between consecutive values in the resulting string
353   *     (but not at the start or end)
354   * @param array an array of {@code char} values, possibly empty
355   */
356  public static String join(String separator, char... array) {
357    checkNotNull(separator);
358    int len = array.length;
359    if (len == 0) {
360      return "";
361    }
362
363    StringBuilder builder = new StringBuilder(len + separator.length() * (len - 1));
364    builder.append(array[0]);
365    for (int i = 1; i < len; i++) {
366      builder.append(separator).append(array[i]);
367    }
368    return builder.toString();
369  }
370
371  /**
372   * Returns a comparator that compares two {@code char} arrays <a
373   * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>; not advisable
374   * for sorting user-visible strings as the ordering may not match the conventions of the user's
375   * locale. That is, it compares, using {@link #compare(char, char)}), the first pair of values
376   * that follow any common prefix, or when one array is a prefix of the other, treats the shorter
377   * array as the lesser. For example, {@code [] < ['a'] < ['a', 'b'] < ['b']}.
378   *
379   * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
380   * support only identity equality), but it is consistent with {@link Arrays#equals(char[],
381   * char[])}.
382   *
383   * @since 2.0
384   */
385  public static Comparator<char[]> lexicographicalComparator() {
386    return LexicographicalComparator.INSTANCE;
387  }
388
389  private enum LexicographicalComparator implements Comparator<char[]> {
390    INSTANCE;
391
392    @Override
393    public int compare(char[] left, char[] right) {
394      int minLength = Math.min(left.length, right.length);
395      for (int i = 0; i < minLength; i++) {
396        int result = Character.compare(left[i], right[i]);
397        if (result != 0) {
398          return result;
399        }
400      }
401      return left.length - right.length;
402    }
403
404    @Override
405    public String toString() {
406      return "Chars.lexicographicalComparator()";
407    }
408  }
409
410  /**
411   * Copies a collection of {@code Character} instances into a new array of primitive {@code char}
412   * values.
413   *
414   * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}.
415   * Calling this method is as thread-safe as calling that method.
416   *
417   * @param collection a collection of {@code Character} objects
418   * @return an array containing the same values as {@code collection}, in the same order, converted
419   *     to primitives
420   * @throws NullPointerException if {@code collection} or any of its elements is null
421   */
422  public static char[] toArray(Collection<Character> collection) {
423    if (collection instanceof CharArrayAsList) {
424      return ((CharArrayAsList) collection).toCharArray();
425    }
426
427    Object[] boxedArray = collection.toArray();
428    int len = boxedArray.length;
429    char[] array = new char[len];
430    for (int i = 0; i < len; i++) {
431      // checkNotNull for GWT (do not optimize)
432      array[i] = (Character) checkNotNull(boxedArray[i]);
433    }
434    return array;
435  }
436
437  /**
438   * Sorts the elements of {@code array} in descending order.
439   *
440   * @since 23.1
441   */
442  public static void sortDescending(char[] array) {
443    checkNotNull(array);
444    sortDescending(array, 0, array.length);
445  }
446
447  /**
448   * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
449   * exclusive in descending order.
450   *
451   * @since 23.1
452   */
453  public static void sortDescending(char[] array, int fromIndex, int toIndex) {
454    checkNotNull(array);
455    checkPositionIndexes(fromIndex, toIndex, array.length);
456    Arrays.sort(array, fromIndex, toIndex);
457    reverse(array, fromIndex, toIndex);
458  }
459
460  /**
461   * Reverses the elements of {@code array}. This is equivalent to {@code
462   * Collections.reverse(Chars.asList(array))}, but is likely to be more efficient.
463   *
464   * @since 23.1
465   */
466  public static void reverse(char[] array) {
467    checkNotNull(array);
468    reverse(array, 0, array.length);
469  }
470
471  /**
472   * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
473   * exclusive. This is equivalent to {@code
474   * Collections.reverse(Chars.asList(array).subList(fromIndex, toIndex))}, but is likely to be more
475   * efficient.
476   *
477   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
478   *     {@code toIndex > fromIndex}
479   * @since 23.1
480   */
481  public static void reverse(char[] array, int fromIndex, int toIndex) {
482    checkNotNull(array);
483    checkPositionIndexes(fromIndex, toIndex, array.length);
484    for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) {
485      char tmp = array[i];
486      array[i] = array[j];
487      array[j] = tmp;
488    }
489  }
490
491  /**
492   * Performs a right rotation of {@code array} of "distance" places, so that the first element is
493   * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
494   * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Chars.asList(array),
495   * distance)}, but is considerably faster and avoids allocation and garbage collection.
496   *
497   * <p>The provided "distance" may be negative, which will rotate left.
498   *
499   * @since 32.0.0
500   */
501  public static void rotate(char[] array, int distance) {
502    rotate(array, distance, 0, array.length);
503  }
504
505  /**
506   * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
507   * toIndex} exclusive. This is equivalent to {@code
508   * Collections.rotate(Chars.asList(array).subList(fromIndex, toIndex), distance)}, but is
509   * considerably faster and avoids allocations and garbage collection.
510   *
511   * <p>The provided "distance" may be negative, which will rotate left.
512   *
513   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
514   *     {@code toIndex > fromIndex}
515   * @since 32.0.0
516   */
517  public static void rotate(char[] array, int distance, int fromIndex, int toIndex) {
518    // See Ints.rotate for more details about possible algorithms here.
519    checkNotNull(array);
520    checkPositionIndexes(fromIndex, toIndex, array.length);
521    if (array.length <= 1) {
522      return;
523    }
524
525    int length = toIndex - fromIndex;
526    // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
527    // places left to rotate.
528    int m = -distance % length;
529    m = (m < 0) ? m + length : m;
530    // The current index of what will become the first element of the rotated section.
531    int newFirstIndex = m + fromIndex;
532    if (newFirstIndex == fromIndex) {
533      return;
534    }
535
536    reverse(array, fromIndex, newFirstIndex);
537    reverse(array, newFirstIndex, toIndex);
538    reverse(array, fromIndex, toIndex);
539  }
540
541  /**
542   * Returns a fixed-size list backed by the specified array, similar to {@link
543   * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to
544   * set a value to {@code null} will result in a {@link NullPointerException}.
545   *
546   * <p>The returned list maintains the values, but not the identities, of {@code Character} objects
547   * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
548   * the returned list is unspecified.
549   *
550   * <p>The returned list is serializable.
551   *
552   * @param backingArray the array to back the list
553   * @return a list view of the array
554   */
555  public static List<Character> asList(char... backingArray) {
556    if (backingArray.length == 0) {
557      return Collections.emptyList();
558    }
559    return new CharArrayAsList(backingArray);
560  }
561
562  @GwtCompatible
563  private static class CharArrayAsList extends AbstractList<Character>
564      implements RandomAccess, Serializable {
565    final char[] array;
566    final int start;
567    final int end;
568
569    CharArrayAsList(char[] array) {
570      this(array, 0, array.length);
571    }
572
573    CharArrayAsList(char[] array, int start, int end) {
574      this.array = array;
575      this.start = start;
576      this.end = end;
577    }
578
579    @Override
580    public int size() {
581      return end - start;
582    }
583
584    @Override
585    public boolean isEmpty() {
586      return false;
587    }
588
589    @Override
590    public Character get(int index) {
591      checkElementIndex(index, size());
592      return array[start + index];
593    }
594
595    @Override
596    public boolean contains(@CheckForNull Object target) {
597      // Overridden to prevent a ton of boxing
598      return (target instanceof Character)
599          && Chars.indexOf(array, (Character) target, start, end) != -1;
600    }
601
602    @Override
603    public int indexOf(@CheckForNull Object target) {
604      // Overridden to prevent a ton of boxing
605      if (target instanceof Character) {
606        int i = Chars.indexOf(array, (Character) target, start, end);
607        if (i >= 0) {
608          return i - start;
609        }
610      }
611      return -1;
612    }
613
614    @Override
615    public int lastIndexOf(@CheckForNull Object target) {
616      // Overridden to prevent a ton of boxing
617      if (target instanceof Character) {
618        int i = Chars.lastIndexOf(array, (Character) target, start, end);
619        if (i >= 0) {
620          return i - start;
621        }
622      }
623      return -1;
624    }
625
626    @Override
627    public Character set(int index, Character element) {
628      checkElementIndex(index, size());
629      char oldValue = array[start + index];
630      // checkNotNull for GWT (do not optimize)
631      array[start + index] = checkNotNull(element);
632      return oldValue;
633    }
634
635    @Override
636    public List<Character> subList(int fromIndex, int toIndex) {
637      int size = size();
638      checkPositionIndexes(fromIndex, toIndex, size);
639      if (fromIndex == toIndex) {
640        return Collections.emptyList();
641      }
642      return new CharArrayAsList(array, start + fromIndex, start + toIndex);
643    }
644
645    @Override
646    public boolean equals(@CheckForNull Object object) {
647      if (object == this) {
648        return true;
649      }
650      if (object instanceof CharArrayAsList) {
651        CharArrayAsList that = (CharArrayAsList) object;
652        int size = size();
653        if (that.size() != size) {
654          return false;
655        }
656        for (int i = 0; i < size; i++) {
657          if (array[start + i] != that.array[that.start + i]) {
658            return false;
659          }
660        }
661        return true;
662      }
663      return super.equals(object);
664    }
665
666    @Override
667    public int hashCode() {
668      int result = 1;
669      for (int i = start; i < end; i++) {
670        result = 31 * result + Chars.hashCode(array[i]);
671      }
672      return result;
673    }
674
675    @Override
676    public String toString() {
677      StringBuilder builder = new StringBuilder(size() * 3);
678      builder.append('[').append(array[start]);
679      for (int i = start + 1; i < end; i++) {
680        builder.append(", ").append(array[i]);
681      }
682      return builder.append(']').toString();
683    }
684
685    char[] toCharArray() {
686      return Arrays.copyOfRange(array, start, end);
687    }
688
689    private static final long serialVersionUID = 0;
690  }
691}