1/*
2 * Copyright (C) 2008 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.common.primitives;
18
19import static com.google.common.base.Preconditions.checkArgument;
20import static com.google.common.base.Preconditions.checkElementIndex;
21import static com.google.common.base.Preconditions.checkNotNull;
22import static com.google.common.base.Preconditions.checkPositionIndexes;
23
24import com.google.common.annotations.GwtCompatible;
25
26import java.io.Serializable;
27import java.util.AbstractList;
28import java.util.Collection;
29import java.util.Collections;
30import java.util.Comparator;
31import java.util.List;
32import java.util.RandomAccess;
33
34/**
35 * Static utility methods pertaining to {@code char} primitives, that are not
36 * already found in either {@link Character} or {@link Arrays}.
37 *
38 * <p>All the operations in this class treat {@code char} values strictly
39 * numerically; they are neither Unicode-aware nor locale-dependent.
40 *
41 * @author Kevin Bourrillion
42 * @since 1.0
43 */
44@GwtCompatible(emulated = true)
45public final class Chars {
46  private Chars() {}
47
48  /**
49   * The number of bytes required to represent a primitive {@code char}
50   * value.
51   */
52  public static final int BYTES = Character.SIZE / Byte.SIZE;
53
54  /**
55   * Returns a hash code for {@code value}; equal to the result of invoking
56   * {@code ((Character) value).hashCode()}.
57   *
58   * @param value a primitive {@code char} value
59   * @return a hash code for the value
60   */
61  public static int hashCode(char value) {
62    return value;
63  }
64
65  /**
66   * Returns the {@code char} value that is equal to {@code value}, if possible.
67   *
68   * @param value any value in the range of the {@code char} type
69   * @return the {@code char} value that equals {@code value}
70   * @throws IllegalArgumentException if {@code value} is greater than {@link
71   *     Character#MAX_VALUE} or less than {@link Character#MIN_VALUE}
72   */
73  public static char checkedCast(long value) {
74    char result = (char) value;
75    checkArgument(result == value, "Out of range: %s", value);
76    return result;
77  }
78
79  /**
80   * Returns the {@code char} nearest in value to {@code value}.
81   *
82   * @param value any {@code long} value
83   * @return the same value cast to {@code char} if it is in the range of the
84   *     {@code char} type, {@link Character#MAX_VALUE} if it is too large,
85   *     or {@link Character#MIN_VALUE} if it is too small
86   */
87  public static char saturatedCast(long value) {
88    if (value > Character.MAX_VALUE) {
89      return Character.MAX_VALUE;
90    }
91    if (value < Character.MIN_VALUE) {
92      return Character.MIN_VALUE;
93    }
94    return (char) value;
95  }
96
97  /**
98   * Compares the two specified {@code char} values. The sign of the value
99   * returned is the same as that of {@code ((Character) a).compareTo(b)}.
100   *
101   * @param a the first {@code char} to compare
102   * @param b the second {@code char} to compare
103   * @return a negative value if {@code a} is less than {@code b}; a positive
104   *     value if {@code a} is greater than {@code b}; or zero if they are equal
105   */
106  public static int compare(char a, char b) {
107    return a - b; // safe due to restricted range
108  }
109
110  /**
111   * Returns {@code true} if {@code target} is present as an element anywhere in
112   * {@code array}.
113   *
114   * @param array an array of {@code char} values, possibly empty
115   * @param target a primitive {@code char} value
116   * @return {@code true} if {@code array[i] == target} for some value of {@code
117   *     i}
118   */
119  public static boolean contains(char[] array, char target) {
120    for (char value : array) {
121      if (value == target) {
122        return true;
123      }
124    }
125    return false;
126  }
127
128  /**
129   * Returns the index of the first appearance of the value {@code target} in
130   * {@code array}.
131   *
132   * @param array an array of {@code char} values, possibly empty
133   * @param target a primitive {@code char} value
134   * @return the least index {@code i} for which {@code array[i] == target}, or
135   *     {@code -1} if no such index exists.
136   */
137  public static int indexOf(char[] array, char target) {
138    return indexOf(array, target, 0, array.length);
139  }
140
141  // TODO(kevinb): consider making this public
142  private static int indexOf(
143      char[] array, char target, int start, int end) {
144    for (int i = start; i < end; i++) {
145      if (array[i] == target) {
146        return i;
147      }
148    }
149    return -1;
150  }
151
152  /**
153   * Returns the start position of the first occurrence of the specified {@code
154   * target} within {@code array}, or {@code -1} if there is no such occurrence.
155   *
156   * <p>More formally, returns the lowest index {@code i} such that {@code
157   * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
158   * the same elements as {@code target}.
159   *
160   * @param array the array to search for the sequence {@code target}
161   * @param target the array to search for as a sub-sequence of {@code array}
162   */
163  public static int indexOf(char[] array, char[] target) {
164    checkNotNull(array, "array");
165    checkNotNull(target, "target");
166    if (target.length == 0) {
167      return 0;
168    }
169
170    outer:
171    for (int i = 0; i < array.length - target.length + 1; i++) {
172      for (int j = 0; j < target.length; j++) {
173        if (array[i + j] != target[j]) {
174          continue outer;
175        }
176      }
177      return i;
178    }
179    return -1;
180  }
181
182  /**
183   * Returns the index of the last appearance of the value {@code target} in
184   * {@code array}.
185   *
186   * @param array an array of {@code char} values, possibly empty
187   * @param target a primitive {@code char} value
188   * @return the greatest index {@code i} for which {@code array[i] == target},
189   *     or {@code -1} if no such index exists.
190   */
191  public static int lastIndexOf(char[] array, char target) {
192    return lastIndexOf(array, target, 0, array.length);
193  }
194
195  // TODO(kevinb): consider making this public
196  private static int lastIndexOf(
197      char[] array, char target, int start, int end) {
198    for (int i = end - 1; i >= start; i--) {
199      if (array[i] == target) {
200        return i;
201      }
202    }
203    return -1;
204  }
205
206  /**
207   * Returns the least value present in {@code array}.
208   *
209   * @param array a <i>nonempty</i> array of {@code char} values
210   * @return the value present in {@code array} that is less than or equal to
211   *     every other value in the array
212   * @throws IllegalArgumentException if {@code array} is empty
213   */
214  public static char min(char... array) {
215    checkArgument(array.length > 0);
216    char min = array[0];
217    for (int i = 1; i < array.length; i++) {
218      if (array[i] < min) {
219        min = array[i];
220      }
221    }
222    return min;
223  }
224
225  /**
226   * Returns the greatest value present in {@code array}.
227   *
228   * @param array a <i>nonempty</i> array of {@code char} values
229   * @return the value present in {@code array} that is greater than or equal to
230   *     every other value in the array
231   * @throws IllegalArgumentException if {@code array} is empty
232   */
233  public static char max(char... array) {
234    checkArgument(array.length > 0);
235    char max = array[0];
236    for (int i = 1; i < array.length; i++) {
237      if (array[i] > max) {
238        max = array[i];
239      }
240    }
241    return max;
242  }
243
244  /**
245   * Returns the values from each provided array combined into a single array.
246   * For example, {@code concat(new char[] {a, b}, new char[] {}, new
247   * char[] {c}} returns the array {@code {a, b, c}}.
248   *
249   * @param arrays zero or more {@code char} arrays
250   * @return a single array containing all the values from the source arrays, in
251   *     order
252   */
253  public static char[] concat(char[]... arrays) {
254    int length = 0;
255    for (char[] array : arrays) {
256      length += array.length;
257    }
258    char[] result = new char[length];
259    int pos = 0;
260    for (char[] array : arrays) {
261      System.arraycopy(array, 0, result, pos, array.length);
262      pos += array.length;
263    }
264    return result;
265  }
266
267  /**
268   * Returns an array containing the same values as {@code array}, but
269   * guaranteed to be of a specified minimum length. If {@code array} already
270   * has a length of at least {@code minLength}, it is returned directly.
271   * Otherwise, a new array of size {@code minLength + padding} is returned,
272   * containing the values of {@code array}, and zeroes in the remaining places.
273   *
274   * @param array the source array
275   * @param minLength the minimum length the returned array must guarantee
276   * @param padding an extra amount to "grow" the array by if growth is
277   *     necessary
278   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is
279   *     negative
280   * @return an array containing the values of {@code array}, with guaranteed
281   *     minimum length {@code minLength}
282   */
283  public static char[] ensureCapacity(
284      char[] array, int minLength, int padding) {
285    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
286    checkArgument(padding >= 0, "Invalid padding: %s", padding);
287    return (array.length < minLength)
288        ? copyOf(array, minLength + padding)
289        : array;
290  }
291
292  // Arrays.copyOf() requires Java 6
293  private static char[] copyOf(char[] original, int length) {
294    char[] copy = new char[length];
295    System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
296    return copy;
297  }
298
299  /**
300   * Returns a string containing the supplied {@code char} values separated
301   * by {@code separator}. For example, {@code join("-", '1', '2', '3')} returns
302   * the string {@code "1-2-3"}.
303   *
304   * @param separator the text that should appear between consecutive values in
305   *     the resulting string (but not at the start or end)
306   * @param array an array of {@code char} values, possibly empty
307   */
308  public static String join(String separator, char... array) {
309    checkNotNull(separator);
310    int len = array.length;
311    if (len == 0) {
312      return "";
313    }
314
315    StringBuilder builder
316        = new StringBuilder(len + separator.length() * (len - 1));
317    builder.append(array[0]);
318    for (int i = 1; i < len; i++) {
319      builder.append(separator).append(array[i]);
320    }
321    return builder.toString();
322  }
323
324  /**
325   * Returns a comparator that compares two {@code char} arrays
326   * lexicographically. That is, it compares, using {@link
327   * #compare(char, char)}), the first pair of values that follow any
328   * common prefix, or when one array is a prefix of the other, treats the
329   * shorter array as the lesser. For example,
330   * {@code [] < ['a'] < ['a', 'b'] < ['b']}.
331   *
332   * <p>The returned comparator is inconsistent with {@link
333   * Object#equals(Object)} (since arrays support only identity equality), but
334   * it is consistent with {@link Arrays#equals(char[], char[])}.
335   *
336   * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
337   *     Lexicographical order article at Wikipedia</a>
338   * @since 2.0
339   */
340  public static Comparator<char[]> lexicographicalComparator() {
341    return LexicographicalComparator.INSTANCE;
342  }
343
344  private enum LexicographicalComparator implements Comparator<char[]> {
345    INSTANCE;
346
347    @Override
348    public int compare(char[] left, char[] right) {
349      int minLength = Math.min(left.length, right.length);
350      for (int i = 0; i < minLength; i++) {
351        int result = Chars.compare(left[i], right[i]);
352        if (result != 0) {
353          return result;
354        }
355      }
356      return left.length - right.length;
357    }
358  }
359
360  /**
361   * Copies a collection of {@code Character} instances into a new array of
362   * primitive {@code char} values.
363   *
364   * <p>Elements are copied from the argument collection as if by {@code
365   * collection.toArray()}.  Calling this method is as thread-safe as calling
366   * that method.
367   *
368   * @param collection a collection of {@code Character} objects
369   * @return an array containing the same values as {@code collection}, in the
370   *     same order, converted to primitives
371   * @throws NullPointerException if {@code collection} or any of its elements
372   *     is null
373   */
374  public static char[] toArray(Collection<Character> collection) {
375    if (collection instanceof CharArrayAsList) {
376      return ((CharArrayAsList) collection).toCharArray();
377    }
378
379    Object[] boxedArray = collection.toArray();
380    int len = boxedArray.length;
381    char[] array = new char[len];
382    for (int i = 0; i < len; i++) {
383      // checkNotNull for GWT (do not optimize)
384      array[i] = (Character) checkNotNull(boxedArray[i]);
385    }
386    return array;
387  }
388
389  /**
390   * Returns a fixed-size list backed by the specified array, similar to {@link
391   * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
392   * but any attempt to set a value to {@code null} will result in a {@link
393   * NullPointerException}.
394   *
395   * <p>The returned list maintains the values, but not the identities, of
396   * {@code Character} objects written to or read from it.  For example, whether
397   * {@code list.get(0) == list.get(0)} is true for the returned list is
398   * unspecified.
399   *
400   * @param backingArray the array to back the list
401   * @return a list view of the array
402   */
403  public static List<Character> asList(char... backingArray) {
404    if (backingArray.length == 0) {
405      return Collections.emptyList();
406    }
407    return new CharArrayAsList(backingArray);
408  }
409
410  @GwtCompatible
411  private static class CharArrayAsList extends AbstractList<Character>
412      implements RandomAccess, Serializable {
413    final char[] array;
414    final int start;
415    final int end;
416
417    CharArrayAsList(char[] array) {
418      this(array, 0, array.length);
419    }
420
421    CharArrayAsList(char[] array, int start, int end) {
422      this.array = array;
423      this.start = start;
424      this.end = end;
425    }
426
427    @Override public int size() {
428      return end - start;
429    }
430
431    @Override public boolean isEmpty() {
432      return false;
433    }
434
435    @Override public Character get(int index) {
436      checkElementIndex(index, size());
437      return array[start + index];
438    }
439
440    @Override public boolean contains(Object target) {
441      // Overridden to prevent a ton of boxing
442      return (target instanceof Character)
443          && Chars.indexOf(array, (Character) target, start, end) != -1;
444    }
445
446    @Override public int indexOf(Object target) {
447      // Overridden to prevent a ton of boxing
448      if (target instanceof Character) {
449        int i = Chars.indexOf(array, (Character) target, start, end);
450        if (i >= 0) {
451          return i - start;
452        }
453      }
454      return -1;
455    }
456
457    @Override public int lastIndexOf(Object target) {
458      // Overridden to prevent a ton of boxing
459      if (target instanceof Character) {
460        int i = Chars.lastIndexOf(array, (Character) target, start, end);
461        if (i >= 0) {
462          return i - start;
463        }
464      }
465      return -1;
466    }
467
468    @Override public Character set(int index, Character element) {
469      checkElementIndex(index, size());
470      char oldValue = array[start + index];
471      array[start + index] = checkNotNull(element);  // checkNotNull for GWT (do not optimize)
472      return oldValue;
473    }
474
475    @Override public List<Character> subList(int fromIndex, int toIndex) {
476      int size = size();
477      checkPositionIndexes(fromIndex, toIndex, size);
478      if (fromIndex == toIndex) {
479        return Collections.emptyList();
480      }
481      return new CharArrayAsList(array, start + fromIndex, start + toIndex);
482    }
483
484    @Override public boolean equals(Object object) {
485      if (object == this) {
486        return true;
487      }
488      if (object instanceof CharArrayAsList) {
489        CharArrayAsList that = (CharArrayAsList) object;
490        int size = size();
491        if (that.size() != size) {
492          return false;
493        }
494        for (int i = 0; i < size; i++) {
495          if (array[start + i] != that.array[that.start + i]) {
496            return false;
497          }
498        }
499        return true;
500      }
501      return super.equals(object);
502    }
503
504    @Override public int hashCode() {
505      int result = 1;
506      for (int i = start; i < end; i++) {
507        result = 31 * result + Chars.hashCode(array[i]);
508      }
509      return result;
510    }
511
512    @Override public String toString() {
513      StringBuilder builder = new StringBuilder(size() * 3);
514      builder.append('[').append(array[start]);
515      for (int i = start + 1; i < end; i++) {
516        builder.append(", ").append(array[i]);
517      }
518      return builder.append(']').toString();
519    }
520
521    char[] toCharArray() {
522      // Arrays.copyOfRange() requires Java 6
523      int size = size();
524      char[] result = new char[size];
525      System.arraycopy(array, start, result, 0, size);
526      return result;
527    }
528
529    private static final long serialVersionUID = 0;
530  }
531}
532
533