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