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 org.checkerframework.checker.nullness.qual.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 <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)
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 {@code ((Character)
061   * 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 i}
126   */
127  public static boolean contains(char[] array, char target) {
128    for (char value : array) {
129      if (value == target) {
130        return true;
131      }
132    }
133    return false;
134  }
135
136  /**
137   * Returns the index of the first appearance of the value {@code target} in {@code array}.
138   *
139   * @param array an array of {@code char} values, possibly empty
140   * @param target a primitive {@code char} value
141   * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no
142   *     such index exists.
143   */
144  public static int indexOf(char[] array, char target) {
145    return indexOf(array, target, 0, array.length);
146  }
147
148  // TODO(kevinb): consider making this public
149  private static int indexOf(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 target} within
160   * {@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 Arrays.copyOfRange(array,
163   * i, i + target.length)} contains exactly the same elements as {@code target}.
164   *
165   * @param array the array to search for the sequence {@code target}
166   * @param target the array to search for as a sub-sequence of {@code array}
167   */
168  public static int indexOf(char[] array, char[] target) {
169    checkNotNull(array, "array");
170    checkNotNull(target, "target");
171    if (target.length == 0) {
172      return 0;
173    }
174
175    outer:
176    for (int i = 0; i < array.length - target.length + 1; i++) {
177      for (int j = 0; j < target.length; j++) {
178        if (array[i + j] != target[j]) {
179          continue outer;
180        }
181      }
182      return i;
183    }
184    return -1;
185  }
186
187  /**
188   * Returns the index of the last appearance of the value {@code target} in {@code array}.
189   *
190   * @param array an array of {@code char} values, possibly empty
191   * @param target a primitive {@code char} value
192   * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no
193   *     such index exists.
194   */
195  public static int lastIndexOf(char[] array, char target) {
196    return lastIndexOf(array, target, 0, array.length);
197  }
198
199  // TODO(kevinb): consider making this public
200  private static int lastIndexOf(char[] array, char target, int start, int end) {
201    for (int i = end - 1; i >= start; i--) {
202      if (array[i] == target) {
203        return i;
204      }
205    }
206    return -1;
207  }
208
209  /**
210   * Returns the least value present in {@code array}.
211   *
212   * @param array a <i>nonempty</i> array of {@code char} values
213   * @return the value present in {@code array} that is less than or equal to every other value in
214   *     the array
215   * @throws IllegalArgumentException if {@code array} is empty
216   */
217  public static char min(char... array) {
218    checkArgument(array.length > 0);
219    char min = array[0];
220    for (int i = 1; i < array.length; i++) {
221      if (array[i] < min) {
222        min = array[i];
223      }
224    }
225    return min;
226  }
227
228  /**
229   * Returns the greatest value present in {@code array}.
230   *
231   * @param array a <i>nonempty</i> array of {@code char} values
232   * @return the value present in {@code array} that is greater than or equal to every other value
233   *     in the array
234   * @throws IllegalArgumentException if {@code array} is empty
235   */
236  public static char max(char... array) {
237    checkArgument(array.length > 0);
238    char max = array[0];
239    for (int i = 1; i < array.length; i++) {
240      if (array[i] > max) {
241        max = array[i];
242      }
243    }
244    return max;
245  }
246
247  /**
248   * Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}.
249   *
250   * <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned
251   * unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if {@code
252   * value} is greater than {@code max}, {@code max} is returned.
253   *
254   * @param value the {@code char} value to constrain
255   * @param min the lower bound (inclusive) of the range to constrain {@code value} to
256   * @param max the upper bound (inclusive) of the range to constrain {@code value} to
257   * @throws IllegalArgumentException if {@code min > max}
258   * @since 21.0
259   */
260  @Beta
261  public static char constrainToRange(char value, char min, char max) {
262    checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max);
263    return value < min ? min : value < max ? value : max;
264  }
265
266  /**
267   * Returns the values from each provided array combined into a single array. For example, {@code
268   * concat(new char[] {a, b}, new char[] {}, new char[] {c}} returns the array {@code {a, b, c}}.
269   *
270   * @param arrays zero or more {@code char} arrays
271   * @return a single array containing all the values from the source arrays, in order
272   */
273  public static char[] concat(char[]... arrays) {
274    int length = 0;
275    for (char[] array : arrays) {
276      length += array.length;
277    }
278    char[] result = new char[length];
279    int pos = 0;
280    for (char[] array : arrays) {
281      System.arraycopy(array, 0, result, pos, array.length);
282      pos += array.length;
283    }
284    return result;
285  }
286
287  /**
288   * Returns a big-endian representation of {@code value} in a 2-element byte array; equivalent to
289   * {@code ByteBuffer.allocate(2).putChar(value).array()}. For example, the input value {@code
290   * '\\u5432'} would yield the byte array {@code {0x54, 0x32}}.
291   *
292   * <p>If you need to convert and concatenate several values (possibly even of different types),
293   * use a shared {@link java.nio.ByteBuffer} instance, or use {@link
294   * com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer.
295   */
296  @GwtIncompatible // doesn't work
297  public static byte[] toByteArray(char value) {
298    return new byte[] {(byte) (value >> 8), (byte) value};
299  }
300
301  /**
302   * Returns the {@code char} value whose big-endian representation is stored in the first 2 bytes
303   * of {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getChar()}. For example, the
304   * input byte array {@code {0x54, 0x32}} would yield the {@code char} value {@code '\\u5432'}.
305   *
306   * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more
307   * flexibility at little cost in readability.
308   *
309   * @throws IllegalArgumentException if {@code bytes} has fewer than 2 elements
310   */
311  @GwtIncompatible // doesn't work
312  public static char fromByteArray(byte[] bytes) {
313    checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES);
314    return fromBytes(bytes[0], bytes[1]);
315  }
316
317  /**
318   * Returns the {@code char} value whose byte representation is the given 2 bytes, in big-endian
319   * order; equivalent to {@code Chars.fromByteArray(new byte[] {b1, b2})}.
320   *
321   * @since 7.0
322   */
323  @GwtIncompatible // doesn't work
324  public static char fromBytes(byte b1, byte b2) {
325    return (char) ((b1 << 8) | (b2 & 0xFF));
326  }
327
328  /**
329   * Returns an array containing the same values as {@code array}, but guaranteed to be of a
330   * specified minimum length. If {@code array} already has a length of at least {@code minLength},
331   * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is
332   * returned, containing the values of {@code array}, and zeroes in the remaining places.
333   *
334   * @param array the source array
335   * @param minLength the minimum length the returned array must guarantee
336   * @param padding an extra amount to "grow" the array by if growth is necessary
337   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative
338   * @return an array containing the values of {@code array}, with guaranteed minimum length {@code
339   *     minLength}
340   */
341  public static char[] ensureCapacity(char[] array, int minLength, int padding) {
342    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
343    checkArgument(padding >= 0, "Invalid padding: %s", padding);
344    return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array;
345  }
346
347  /**
348   * Returns a string containing the supplied {@code char} values separated by {@code separator}.
349   * For example, {@code join("-", '1', '2', '3')} returns the string {@code "1-2-3"}.
350   *
351   * @param separator the text that should appear between consecutive values in the resulting string
352   *     (but not at the start or end)
353   * @param array an array of {@code char} values, possibly empty
354   */
355  public static String join(String separator, char... array) {
356    checkNotNull(separator);
357    int len = array.length;
358    if (len == 0) {
359      return "";
360    }
361
362    StringBuilder builder = new StringBuilder(len + separator.length() * (len - 1));
363    builder.append(array[0]);
364    for (int i = 1; i < len; i++) {
365      builder.append(separator).append(array[i]);
366    }
367    return builder.toString();
368  }
369
370  /**
371   * Returns a comparator that compares two {@code char} arrays <a
372   * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it
373   * compares, using {@link #compare(char, char)}), the first pair of values that follow any common
374   * prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For
375   * example, {@code [] < ['a'] < ['a', 'b'] < ['b']}.
376   *
377   * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
378   * support only identity equality), but it is consistent with {@link Arrays#equals(char[],
379   * char[])}.
380   *
381   * @since 2.0
382   */
383  public static Comparator<char[]> lexicographicalComparator() {
384    return LexicographicalComparator.INSTANCE;
385  }
386
387  private enum LexicographicalComparator implements Comparator<char[]> {
388    INSTANCE;
389
390    @Override
391    public int compare(char[] left, char[] right) {
392      int minLength = Math.min(left.length, right.length);
393      for (int i = 0; i < minLength; i++) {
394        int result = Chars.compare(left[i], right[i]);
395        if (result != 0) {
396          return result;
397        }
398      }
399      return left.length - right.length;
400    }
401
402    @Override
403    public String toString() {
404      return "Chars.lexicographicalComparator()";
405    }
406  }
407
408  /**
409   * Copies a collection of {@code Character} instances into a new array of primitive {@code char}
410   * values.
411   *
412   * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}.
413   * Calling this method is as thread-safe as calling that method.
414   *
415   * @param collection a collection of {@code Character} objects
416   * @return an array containing the same values as {@code collection}, in the same order, converted
417   *     to primitives
418   * @throws NullPointerException if {@code collection} or any of its elements is null
419   */
420  public static char[] toArray(Collection<Character> collection) {
421    if (collection instanceof CharArrayAsList) {
422      return ((CharArrayAsList) collection).toCharArray();
423    }
424
425    Object[] boxedArray = collection.toArray();
426    int len = boxedArray.length;
427    char[] array = new char[len];
428    for (int i = 0; i < len; i++) {
429      // checkNotNull for GWT (do not optimize)
430      array[i] = (Character) checkNotNull(boxedArray[i]);
431    }
432    return array;
433  }
434
435  /**
436   * Sorts the elements of {@code array} in descending order.
437   *
438   * @since 23.1
439   */
440  public static void sortDescending(char[] array) {
441    checkNotNull(array);
442    sortDescending(array, 0, array.length);
443  }
444
445  /**
446   * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
447   * exclusive in descending order.
448   *
449   * @since 23.1
450   */
451  public static void sortDescending(char[] array, int fromIndex, int toIndex) {
452    checkNotNull(array);
453    checkPositionIndexes(fromIndex, toIndex, array.length);
454    Arrays.sort(array, fromIndex, toIndex);
455    reverse(array, fromIndex, toIndex);
456  }
457
458  /**
459   * Reverses the elements of {@code array}. This is equivalent to {@code
460   * Collections.reverse(Chars.asList(array))}, but is likely to be more efficient.
461   *
462   * @since 23.1
463   */
464  public static void reverse(char[] array) {
465    checkNotNull(array);
466    reverse(array, 0, array.length);
467  }
468
469  /**
470   * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
471   * exclusive. This is equivalent to {@code
472   * Collections.reverse(Chars.asList(array).subList(fromIndex, toIndex))}, but is likely to be more
473   * efficient.
474   *
475   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
476   *     {@code toIndex > fromIndex}
477   * @since 23.1
478   */
479  public static void reverse(char[] array, int fromIndex, int toIndex) {
480    checkNotNull(array);
481    checkPositionIndexes(fromIndex, toIndex, array.length);
482    for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) {
483      char tmp = array[i];
484      array[i] = array[j];
485      array[j] = tmp;
486    }
487  }
488
489  /**
490   * Returns a fixed-size list backed by the specified array, similar to {@link
491   * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to
492   * set a value to {@code null} will result in a {@link NullPointerException}.
493   *
494   * <p>The returned list maintains the values, but not the identities, of {@code Character} objects
495   * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
496   * the returned list is unspecified.
497   *
498   * @param backingArray the array to back the list
499   * @return a list view of the array
500   */
501  public static List<Character> asList(char... backingArray) {
502    if (backingArray.length == 0) {
503      return Collections.emptyList();
504    }
505    return new CharArrayAsList(backingArray);
506  }
507
508  @GwtCompatible
509  private static class CharArrayAsList extends AbstractList<Character>
510      implements RandomAccess, Serializable {
511    final char[] array;
512    final int start;
513    final int end;
514
515    CharArrayAsList(char[] array) {
516      this(array, 0, array.length);
517    }
518
519    CharArrayAsList(char[] array, int start, int end) {
520      this.array = array;
521      this.start = start;
522      this.end = end;
523    }
524
525    @Override
526    public int size() {
527      return end - start;
528    }
529
530    @Override
531    public boolean isEmpty() {
532      return false;
533    }
534
535    @Override
536    public Character get(int index) {
537      checkElementIndex(index, size());
538      return array[start + index];
539    }
540
541    @Override
542    public boolean contains(Object target) {
543      // Overridden to prevent a ton of boxing
544      return (target instanceof Character)
545          && Chars.indexOf(array, (Character) target, start, end) != -1;
546    }
547
548    @Override
549    public int indexOf(Object target) {
550      // Overridden to prevent a ton of boxing
551      if (target instanceof Character) {
552        int i = Chars.indexOf(array, (Character) target, start, end);
553        if (i >= 0) {
554          return i - start;
555        }
556      }
557      return -1;
558    }
559
560    @Override
561    public int lastIndexOf(Object target) {
562      // Overridden to prevent a ton of boxing
563      if (target instanceof Character) {
564        int i = Chars.lastIndexOf(array, (Character) target, start, end);
565        if (i >= 0) {
566          return i - start;
567        }
568      }
569      return -1;
570    }
571
572    @Override
573    public Character set(int index, Character element) {
574      checkElementIndex(index, size());
575      char oldValue = array[start + index];
576      // checkNotNull for GWT (do not optimize)
577      array[start + index] = checkNotNull(element);
578      return oldValue;
579    }
580
581    @Override
582    public List<Character> subList(int fromIndex, int toIndex) {
583      int size = size();
584      checkPositionIndexes(fromIndex, toIndex, size);
585      if (fromIndex == toIndex) {
586        return Collections.emptyList();
587      }
588      return new CharArrayAsList(array, start + fromIndex, start + toIndex);
589    }
590
591    @Override
592    public boolean equals(@Nullable Object object) {
593      if (object == this) {
594        return true;
595      }
596      if (object instanceof CharArrayAsList) {
597        CharArrayAsList that = (CharArrayAsList) object;
598        int size = size();
599        if (that.size() != size) {
600          return false;
601        }
602        for (int i = 0; i < size; i++) {
603          if (array[start + i] != that.array[that.start + i]) {
604            return false;
605          }
606        }
607        return true;
608      }
609      return super.equals(object);
610    }
611
612    @Override
613    public int hashCode() {
614      int result = 1;
615      for (int i = start; i < end; i++) {
616        result = 31 * result + Chars.hashCode(array[i]);
617      }
618      return result;
619    }
620
621    @Override
622    public String toString() {
623      StringBuilder builder = new StringBuilder(size() * 3);
624      builder.append('[').append(array[start]);
625      for (int i = start + 1; i < end; i++) {
626        builder.append(", ").append(array[i]);
627      }
628      return builder.append(']').toString();
629    }
630
631    char[] toCharArray() {
632      return Arrays.copyOfRange(array, start, end);
633    }
634
635    private static final long serialVersionUID = 0;
636  }
637}