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