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