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   * @throws IllegalArgumentException if the total number of elements in {@code arrays} does not fit
274   *     in an {@code int}
275   */
276  public static char[] concat(char[]... arrays) {
277    long length = 0;
278    for (char[] array : arrays) {
279      length += array.length;
280    }
281    char[] result = new char[checkNoOverflow(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  private static int checkNoOverflow(long result) {
291    checkArgument(
292        result == (int) result,
293        "the total number of elements (%s) in the arrays must fit in an int",
294        result);
295    return (int) result;
296  }
297
298  /**
299   * Returns a big-endian representation of {@code value} in a 2-element byte array; equivalent to
300   * {@code ByteBuffer.allocate(2).putChar(value).array()}. For example, the input value {@code
301   * '\\u5432'} would yield the byte array {@code {0x54, 0x32}}.
302   *
303   * <p>If you need to convert and concatenate several values (possibly even of different types),
304   * use a shared {@link java.nio.ByteBuffer} instance, or use {@link
305   * com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer.
306   */
307  @GwtIncompatible // doesn't work
308  public static byte[] toByteArray(char value) {
309    return new byte[] {(byte) (value >> 8), (byte) value};
310  }
311
312  /**
313   * Returns the {@code char} value whose big-endian representation is stored in the first 2 bytes
314   * of {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getChar()}. For example, the
315   * input byte array {@code {0x54, 0x32}} would yield the {@code char} value {@code '\\u5432'}.
316   *
317   * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more
318   * flexibility at little cost in readability.
319   *
320   * @throws IllegalArgumentException if {@code bytes} has fewer than 2 elements
321   */
322  @GwtIncompatible // doesn't work
323  public static char fromByteArray(byte[] bytes) {
324    checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES);
325    return fromBytes(bytes[0], bytes[1]);
326  }
327
328  /**
329   * Returns the {@code char} value whose byte representation is the given 2 bytes, in big-endian
330   * order; equivalent to {@code Chars.fromByteArray(new byte[] {b1, b2})}.
331   *
332   * @since 7.0
333   */
334  @GwtIncompatible // doesn't work
335  public static char fromBytes(byte b1, byte b2) {
336    return (char) ((b1 << 8) | (b2 & 0xFF));
337  }
338
339  /**
340   * Returns an array containing the same values as {@code array}, but guaranteed to be of a
341   * specified minimum length. If {@code array} already has a length of at least {@code minLength},
342   * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is
343   * returned, containing the values of {@code array}, and zeroes in the remaining places.
344   *
345   * @param array the source array
346   * @param minLength the minimum length the returned array must guarantee
347   * @param padding an extra amount to "grow" the array by if growth is necessary
348   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative
349   * @return an array containing the values of {@code array}, with guaranteed minimum length {@code
350   *     minLength}
351   */
352  public static char[] ensureCapacity(char[] array, int minLength, int padding) {
353    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
354    checkArgument(padding >= 0, "Invalid padding: %s", padding);
355    return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array;
356  }
357
358  /**
359   * Returns a string containing the supplied {@code char} values separated by {@code separator}.
360   * For example, {@code join("-", '1', '2', '3')} returns the string {@code "1-2-3"}.
361   *
362   * @param separator the text that should appear between consecutive values in the resulting string
363   *     (but not at the start or end)
364   * @param array an array of {@code char} values, possibly empty
365   */
366  public static String join(String separator, char... array) {
367    checkNotNull(separator);
368    int len = array.length;
369    if (len == 0) {
370      return "";
371    }
372
373    StringBuilder builder = new StringBuilder(len + separator.length() * (len - 1));
374    builder.append(array[0]);
375    for (int i = 1; i < len; i++) {
376      builder.append(separator).append(array[i]);
377    }
378    return builder.toString();
379  }
380
381  /**
382   * Returns a comparator that compares two {@code char} arrays <a
383   * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>; not advisable
384   * for sorting user-visible strings as the ordering may not match the conventions of the user's
385   * locale. That is, it compares, using {@link #compare(char, char)}), the first pair of values
386   * that follow any common prefix, or when one array is a prefix of the other, treats the shorter
387   * array as the lesser. For example, {@code [] < ['a'] < ['a', 'b'] < ['b']}.
388   *
389   * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
390   * support only identity equality), but it is consistent with {@link Arrays#equals(char[],
391   * char[])}.
392   *
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 = Character.compare(left[i], right[i]);
407        if (result != 0) {
408          return result;
409        }
410      }
411      return left.length - right.length;
412    }
413
414    @Override
415    public String toString() {
416      return "Chars.lexicographicalComparator()";
417    }
418  }
419
420  /**
421   * Copies a collection of {@code Character} instances into a new array of primitive {@code char}
422   * values.
423   *
424   * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}.
425   * Calling this method is as thread-safe as calling that method.
426   *
427   * @param collection a collection of {@code Character} objects
428   * @return an array containing the same values as {@code collection}, in the same order, converted
429   *     to primitives
430   * @throws NullPointerException if {@code collection} or any of its elements is null
431   */
432  public static char[] toArray(Collection<Character> collection) {
433    if (collection instanceof CharArrayAsList) {
434      return ((CharArrayAsList) collection).toCharArray();
435    }
436
437    Object[] boxedArray = collection.toArray();
438    int len = boxedArray.length;
439    char[] array = new char[len];
440    for (int i = 0; i < len; i++) {
441      // checkNotNull for GWT (do not optimize)
442      array[i] = (Character) checkNotNull(boxedArray[i]);
443    }
444    return array;
445  }
446
447  /**
448   * Sorts the elements of {@code array} in descending order.
449   *
450   * @since 23.1
451   */
452  public static void sortDescending(char[] array) {
453    checkNotNull(array);
454    sortDescending(array, 0, array.length);
455  }
456
457  /**
458   * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
459   * exclusive in descending order.
460   *
461   * @since 23.1
462   */
463  public static void sortDescending(char[] array, int fromIndex, int toIndex) {
464    checkNotNull(array);
465    checkPositionIndexes(fromIndex, toIndex, array.length);
466    Arrays.sort(array, fromIndex, toIndex);
467    reverse(array, fromIndex, toIndex);
468  }
469
470  /**
471   * Reverses the elements of {@code array}. This is equivalent to {@code
472   * Collections.reverse(Chars.asList(array))}, but is likely to be more efficient.
473   *
474   * @since 23.1
475   */
476  public static void reverse(char[] array) {
477    checkNotNull(array);
478    reverse(array, 0, array.length);
479  }
480
481  /**
482   * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
483   * exclusive. This is equivalent to {@code
484   * Collections.reverse(Chars.asList(array).subList(fromIndex, toIndex))}, but is likely to be more
485   * efficient.
486   *
487   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
488   *     {@code toIndex > fromIndex}
489   * @since 23.1
490   */
491  public static void reverse(char[] array, int fromIndex, int toIndex) {
492    checkNotNull(array);
493    checkPositionIndexes(fromIndex, toIndex, array.length);
494    for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) {
495      char tmp = array[i];
496      array[i] = array[j];
497      array[j] = tmp;
498    }
499  }
500
501  /**
502   * Performs a right rotation of {@code array} of "distance" places, so that the first element is
503   * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
504   * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Chars.asList(array),
505   * distance)}, but is considerably faster and avoids allocation and garbage collection.
506   *
507   * <p>The provided "distance" may be negative, which will rotate left.
508   *
509   * @since 32.0.0
510   */
511  public static void rotate(char[] array, int distance) {
512    rotate(array, distance, 0, array.length);
513  }
514
515  /**
516   * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
517   * toIndex} exclusive. This is equivalent to {@code
518   * Collections.rotate(Chars.asList(array).subList(fromIndex, toIndex), distance)}, but is
519   * considerably faster and avoids allocations and garbage collection.
520   *
521   * <p>The provided "distance" may be negative, which will rotate left.
522   *
523   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
524   *     {@code toIndex > fromIndex}
525   * @since 32.0.0
526   */
527  public static void rotate(char[] array, int distance, int fromIndex, int toIndex) {
528    // See Ints.rotate for more details about possible algorithms here.
529    checkNotNull(array);
530    checkPositionIndexes(fromIndex, toIndex, array.length);
531    if (array.length <= 1) {
532      return;
533    }
534
535    int length = toIndex - fromIndex;
536    // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
537    // places left to rotate.
538    int m = -distance % length;
539    m = (m < 0) ? m + length : m;
540    // The current index of what will become the first element of the rotated section.
541    int newFirstIndex = m + fromIndex;
542    if (newFirstIndex == fromIndex) {
543      return;
544    }
545
546    reverse(array, fromIndex, newFirstIndex);
547    reverse(array, newFirstIndex, toIndex);
548    reverse(array, fromIndex, toIndex);
549  }
550
551  /**
552   * Returns a fixed-size list backed by the specified array, similar to {@link
553   * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to
554   * set a value to {@code null} will result in a {@link NullPointerException}.
555   *
556   * <p>The returned list maintains the values, but not the identities, of {@code Character} objects
557   * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
558   * the returned list is unspecified.
559   *
560   * <p>The returned list is serializable.
561   *
562   * @param backingArray the array to back the list
563   * @return a list view of the array
564   */
565  public static List<Character> asList(char... backingArray) {
566    if (backingArray.length == 0) {
567      return Collections.emptyList();
568    }
569    return new CharArrayAsList(backingArray);
570  }
571
572  @GwtCompatible
573  private static class CharArrayAsList extends AbstractList<Character>
574      implements RandomAccess, Serializable {
575    final char[] array;
576    final int start;
577    final int end;
578
579    CharArrayAsList(char[] array) {
580      this(array, 0, array.length);
581    }
582
583    CharArrayAsList(char[] array, int start, int end) {
584      this.array = array;
585      this.start = start;
586      this.end = end;
587    }
588
589    @Override
590    public int size() {
591      return end - start;
592    }
593
594    @Override
595    public boolean isEmpty() {
596      return false;
597    }
598
599    @Override
600    public Character get(int index) {
601      checkElementIndex(index, size());
602      return array[start + index];
603    }
604
605    @Override
606    public boolean contains(@CheckForNull Object target) {
607      // Overridden to prevent a ton of boxing
608      return (target instanceof Character)
609          && Chars.indexOf(array, (Character) target, start, end) != -1;
610    }
611
612    @Override
613    public int indexOf(@CheckForNull Object target) {
614      // Overridden to prevent a ton of boxing
615      if (target instanceof Character) {
616        int i = Chars.indexOf(array, (Character) target, start, end);
617        if (i >= 0) {
618          return i - start;
619        }
620      }
621      return -1;
622    }
623
624    @Override
625    public int lastIndexOf(@CheckForNull Object target) {
626      // Overridden to prevent a ton of boxing
627      if (target instanceof Character) {
628        int i = Chars.lastIndexOf(array, (Character) target, start, end);
629        if (i >= 0) {
630          return i - start;
631        }
632      }
633      return -1;
634    }
635
636    @Override
637    public Character set(int index, Character element) {
638      checkElementIndex(index, size());
639      char oldValue = array[start + index];
640      // checkNotNull for GWT (do not optimize)
641      array[start + index] = checkNotNull(element);
642      return oldValue;
643    }
644
645    @Override
646    public List<Character> subList(int fromIndex, int toIndex) {
647      int size = size();
648      checkPositionIndexes(fromIndex, toIndex, size);
649      if (fromIndex == toIndex) {
650        return Collections.emptyList();
651      }
652      return new CharArrayAsList(array, start + fromIndex, start + toIndex);
653    }
654
655    @Override
656    public boolean equals(@CheckForNull Object object) {
657      if (object == this) {
658        return true;
659      }
660      if (object instanceof CharArrayAsList) {
661        CharArrayAsList that = (CharArrayAsList) object;
662        int size = size();
663        if (that.size() != size) {
664          return false;
665        }
666        for (int i = 0; i < size; i++) {
667          if (array[start + i] != that.array[that.start + i]) {
668            return false;
669          }
670        }
671        return true;
672      }
673      return super.equals(object);
674    }
675
676    @Override
677    public int hashCode() {
678      int result = 1;
679      for (int i = start; i < end; i++) {
680        result = 31 * result + Chars.hashCode(array[i]);
681      }
682      return result;
683    }
684
685    @Override
686    public String toString() {
687      StringBuilder builder = new StringBuilder(size() * 3);
688      builder.append('[').append(array[start]);
689      for (int i = start + 1; i < end; i++) {
690        builder.append(", ").append(array[i]);
691      }
692      return builder.append(']').toString();
693    }
694
695    char[] toCharArray() {
696      return Arrays.copyOfRange(array, start, end);
697    }
698
699    private static final long serialVersionUID = 0;
700  }
701}