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