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.CheckForNull; 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 <a 042 * 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) 048@ElementTypesAreNonnullByDefault 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 public static char constrainToRange(char value, char min, char max) { 261 checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max); 262 return value < min ? min : value < max ? value : max; 263 } 264 265 /** 266 * Returns the values from each provided array combined into a single array. For example, {@code 267 * concat(new char[] {a, b}, new char[] {}, new char[] {c}} returns the array {@code {a, b, c}}. 268 * 269 * @param arrays zero or more {@code char} arrays 270 * @return a single array containing all the values from the source arrays, in order 271 */ 272 public static char[] concat(char[]... arrays) { 273 int length = 0; 274 for (char[] array : arrays) { 275 length += array.length; 276 } 277 char[] result = new char[length]; 278 int pos = 0; 279 for (char[] array : arrays) { 280 System.arraycopy(array, 0, result, pos, array.length); 281 pos += array.length; 282 } 283 return result; 284 } 285 286 /** 287 * Returns a big-endian representation of {@code value} in a 2-element byte array; equivalent to 288 * {@code ByteBuffer.allocate(2).putChar(value).array()}. For example, the input value {@code 289 * '\\u5432'} would yield the byte array {@code {0x54, 0x32}}. 290 * 291 * <p>If you need to convert and concatenate several values (possibly even of different types), 292 * use a shared {@link java.nio.ByteBuffer} instance, or use {@link 293 * com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer. 294 */ 295 @GwtIncompatible // doesn't work 296 public static byte[] toByteArray(char value) { 297 return new byte[] {(byte) (value >> 8), (byte) value}; 298 } 299 300 /** 301 * Returns the {@code char} value whose big-endian representation is stored in the first 2 bytes 302 * of {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getChar()}. For example, the 303 * input byte array {@code {0x54, 0x32}} would yield the {@code char} value {@code '\\u5432'}. 304 * 305 * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more 306 * flexibility at little cost in readability. 307 * 308 * @throws IllegalArgumentException if {@code bytes} has fewer than 2 elements 309 */ 310 @GwtIncompatible // doesn't work 311 public static char fromByteArray(byte[] bytes) { 312 checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); 313 return fromBytes(bytes[0], bytes[1]); 314 } 315 316 /** 317 * Returns the {@code char} value whose byte representation is the given 2 bytes, in big-endian 318 * order; equivalent to {@code Chars.fromByteArray(new byte[] {b1, b2})}. 319 * 320 * @since 7.0 321 */ 322 @GwtIncompatible // doesn't work 323 public static char fromBytes(byte b1, byte b2) { 324 return (char) ((b1 << 8) | (b2 & 0xFF)); 325 } 326 327 /** 328 * Returns an array containing the same values as {@code array}, but guaranteed to be of a 329 * specified minimum length. If {@code array} already has a length of at least {@code minLength}, 330 * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is 331 * returned, containing the values of {@code array}, and zeroes in the remaining places. 332 * 333 * @param array the source array 334 * @param minLength the minimum length the returned array must guarantee 335 * @param padding an extra amount to "grow" the array by if growth is necessary 336 * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative 337 * @return an array containing the values of {@code array}, with guaranteed minimum length {@code 338 * minLength} 339 */ 340 public static char[] ensureCapacity(char[] array, int minLength, int padding) { 341 checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); 342 checkArgument(padding >= 0, "Invalid padding: %s", padding); 343 return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array; 344 } 345 346 /** 347 * Returns a string containing the supplied {@code char} values separated by {@code separator}. 348 * For example, {@code join("-", '1', '2', '3')} returns the string {@code "1-2-3"}. 349 * 350 * @param separator the text that should appear between consecutive values in the resulting string 351 * (but not at the start or end) 352 * @param array an array of {@code char} values, possibly empty 353 */ 354 public static String join(String separator, char... array) { 355 checkNotNull(separator); 356 int len = array.length; 357 if (len == 0) { 358 return ""; 359 } 360 361 StringBuilder builder = new StringBuilder(len + separator.length() * (len - 1)); 362 builder.append(array[0]); 363 for (int i = 1; i < len; i++) { 364 builder.append(separator).append(array[i]); 365 } 366 return builder.toString(); 367 } 368 369 /** 370 * Returns a comparator that compares two {@code char} arrays <a 371 * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>; not advisable 372 * for sorting user-visible strings as the ordering may not match the conventions of the user's 373 * locale. That is, it compares, using {@link #compare(char, char)}), the first pair of values 374 * that follow any common prefix, or when one array is a prefix of the other, treats the shorter 375 * array as the lesser. For 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 * Performs a right rotation of {@code array} of "distance" places, so that the first element is 491 * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance 492 * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Chars.asList(array), 493 * distance)}, but is considerably faster and avoids allocation and garbage collection. 494 * 495 * <p>The provided "distance" may be negative, which will rotate left. 496 * 497 * @since 32.0.0 498 */ 499 public static void rotate(char[] array, int distance) { 500 rotate(array, distance, 0, array.length); 501 } 502 503 /** 504 * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code 505 * toIndex} exclusive. This is equivalent to {@code 506 * Collections.rotate(Chars.asList(array).subList(fromIndex, toIndex), distance)}, but is 507 * considerably faster and avoids allocations and garbage collection. 508 * 509 * <p>The provided "distance" may be negative, which will rotate left. 510 * 511 * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or 512 * {@code toIndex > fromIndex} 513 * @since 32.0.0 514 */ 515 public static void rotate(char[] array, int distance, int fromIndex, int toIndex) { 516 // See Ints.rotate for more details about possible algorithms here. 517 checkNotNull(array); 518 checkPositionIndexes(fromIndex, toIndex, array.length); 519 if (array.length <= 1) { 520 return; 521 } 522 523 int length = toIndex - fromIndex; 524 // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many 525 // places left to rotate. 526 int m = -distance % length; 527 m = (m < 0) ? m + length : m; 528 // The current index of what will become the first element of the rotated section. 529 int newFirstIndex = m + fromIndex; 530 if (newFirstIndex == fromIndex) { 531 return; 532 } 533 534 reverse(array, fromIndex, newFirstIndex); 535 reverse(array, newFirstIndex, toIndex); 536 reverse(array, fromIndex, toIndex); 537 } 538 539 /** 540 * Returns a fixed-size list backed by the specified array, similar to {@link 541 * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to 542 * set a value to {@code null} will result in a {@link NullPointerException}. 543 * 544 * <p>The returned list maintains the values, but not the identities, of {@code Character} objects 545 * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for 546 * the returned list is unspecified. 547 * 548 * <p>The returned list is serializable. 549 * 550 * @param backingArray the array to back the list 551 * @return a list view of the array 552 */ 553 public static List<Character> asList(char... backingArray) { 554 if (backingArray.length == 0) { 555 return Collections.emptyList(); 556 } 557 return new CharArrayAsList(backingArray); 558 } 559 560 @GwtCompatible 561 private static class CharArrayAsList extends AbstractList<Character> 562 implements RandomAccess, Serializable { 563 final char[] array; 564 final int start; 565 final int end; 566 567 CharArrayAsList(char[] array) { 568 this(array, 0, array.length); 569 } 570 571 CharArrayAsList(char[] array, int start, int end) { 572 this.array = array; 573 this.start = start; 574 this.end = end; 575 } 576 577 @Override 578 public int size() { 579 return end - start; 580 } 581 582 @Override 583 public boolean isEmpty() { 584 return false; 585 } 586 587 @Override 588 public Character get(int index) { 589 checkElementIndex(index, size()); 590 return array[start + index]; 591 } 592 593 @Override 594 public boolean contains(@CheckForNull Object target) { 595 // Overridden to prevent a ton of boxing 596 return (target instanceof Character) 597 && Chars.indexOf(array, (Character) target, start, end) != -1; 598 } 599 600 @Override 601 public int indexOf(@CheckForNull Object target) { 602 // Overridden to prevent a ton of boxing 603 if (target instanceof Character) { 604 int i = Chars.indexOf(array, (Character) target, start, end); 605 if (i >= 0) { 606 return i - start; 607 } 608 } 609 return -1; 610 } 611 612 @Override 613 public int lastIndexOf(@CheckForNull Object target) { 614 // Overridden to prevent a ton of boxing 615 if (target instanceof Character) { 616 int i = Chars.lastIndexOf(array, (Character) target, start, end); 617 if (i >= 0) { 618 return i - start; 619 } 620 } 621 return -1; 622 } 623 624 @Override 625 public Character set(int index, Character element) { 626 checkElementIndex(index, size()); 627 char oldValue = array[start + index]; 628 // checkNotNull for GWT (do not optimize) 629 array[start + index] = checkNotNull(element); 630 return oldValue; 631 } 632 633 @Override 634 public List<Character> subList(int fromIndex, int toIndex) { 635 int size = size(); 636 checkPositionIndexes(fromIndex, toIndex, size); 637 if (fromIndex == toIndex) { 638 return Collections.emptyList(); 639 } 640 return new CharArrayAsList(array, start + fromIndex, start + toIndex); 641 } 642 643 @Override 644 public boolean equals(@CheckForNull Object object) { 645 if (object == this) { 646 return true; 647 } 648 if (object instanceof CharArrayAsList) { 649 CharArrayAsList that = (CharArrayAsList) object; 650 int size = size(); 651 if (that.size() != size) { 652 return false; 653 } 654 for (int i = 0; i < size; i++) { 655 if (array[start + i] != that.array[that.start + i]) { 656 return false; 657 } 658 } 659 return true; 660 } 661 return super.equals(object); 662 } 663 664 @Override 665 public int hashCode() { 666 int result = 1; 667 for (int i = start; i < end; i++) { 668 result = 31 * result + Chars.hashCode(array[i]); 669 } 670 return result; 671 } 672 673 @Override 674 public String toString() { 675 StringBuilder builder = new StringBuilder(size() * 3); 676 builder.append('[').append(array[start]); 677 for (int i = start + 1; i < end; i++) { 678 builder.append(", ").append(array[i]); 679 } 680 return builder.append(']').toString(); 681 } 682 683 char[] toCharArray() { 684 return Arrays.copyOfRange(array, start, end); 685 } 686 687 private static final long serialVersionUID = 0; 688 } 689}