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.Beta; 023import com.google.common.annotations.GwtCompatible; 024import com.google.common.annotations.GwtIncompatible; 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.checkerframework.checker.nullness.qual.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 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 @Beta 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 */ 273 public static char[] concat(char[]... arrays) { 274 int length = 0; 275 for (char[] array : arrays) { 276 length += array.length; 277 } 278 char[] result = new char[length]; 279 int pos = 0; 280 for (char[] array : arrays) { 281 System.arraycopy(array, 0, result, pos, array.length); 282 pos += array.length; 283 } 284 return result; 285 } 286 287 /** 288 * Returns a big-endian representation of {@code value} in a 2-element byte array; equivalent to 289 * {@code ByteBuffer.allocate(2).putChar(value).array()}. For example, the input value {@code 290 * '\\u5432'} would yield the byte array {@code {0x54, 0x32}}. 291 * 292 * <p>If you need to convert and concatenate several values (possibly even of different types), 293 * use a shared {@link java.nio.ByteBuffer} instance, or use {@link 294 * com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer. 295 */ 296 @GwtIncompatible // doesn't work 297 public static byte[] toByteArray(char value) { 298 return new byte[] {(byte) (value >> 8), (byte) value}; 299 } 300 301 /** 302 * Returns the {@code char} value whose big-endian representation is stored in the first 2 bytes 303 * of {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getChar()}. For example, the 304 * input byte array {@code {0x54, 0x32}} would yield the {@code char} value {@code '\\u5432'}. 305 * 306 * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more 307 * flexibility at little cost in readability. 308 * 309 * @throws IllegalArgumentException if {@code bytes} has fewer than 2 elements 310 */ 311 @GwtIncompatible // doesn't work 312 public static char fromByteArray(byte[] bytes) { 313 checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); 314 return fromBytes(bytes[0], bytes[1]); 315 } 316 317 /** 318 * Returns the {@code char} value whose byte representation is the given 2 bytes, in big-endian 319 * order; equivalent to {@code Chars.fromByteArray(new byte[] {b1, b2})}. 320 * 321 * @since 7.0 322 */ 323 @GwtIncompatible // doesn't work 324 public static char fromBytes(byte b1, byte b2) { 325 return (char) ((b1 << 8) | (b2 & 0xFF)); 326 } 327 328 /** 329 * Returns an array containing the same values as {@code array}, but guaranteed to be of a 330 * specified minimum length. If {@code array} already has a length of at least {@code minLength}, 331 * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is 332 * returned, containing the values of {@code array}, and zeroes in the remaining places. 333 * 334 * @param array the source array 335 * @param minLength the minimum length the returned array must guarantee 336 * @param padding an extra amount to "grow" the array by if growth is necessary 337 * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative 338 * @return an array containing the values of {@code array}, with guaranteed minimum length {@code 339 * minLength} 340 */ 341 public static char[] ensureCapacity(char[] array, int minLength, int padding) { 342 checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); 343 checkArgument(padding >= 0, "Invalid padding: %s", padding); 344 return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array; 345 } 346 347 /** 348 * Returns a string containing the supplied {@code char} values separated by {@code separator}. 349 * For example, {@code join("-", '1', '2', '3')} returns the string {@code "1-2-3"}. 350 * 351 * @param separator the text that should appear between consecutive values in the resulting string 352 * (but not at the start or end) 353 * @param array an array of {@code char} values, possibly empty 354 */ 355 public static String join(String separator, char... array) { 356 checkNotNull(separator); 357 int len = array.length; 358 if (len == 0) { 359 return ""; 360 } 361 362 StringBuilder builder = new StringBuilder(len + separator.length() * (len - 1)); 363 builder.append(array[0]); 364 for (int i = 1; i < len; i++) { 365 builder.append(separator).append(array[i]); 366 } 367 return builder.toString(); 368 } 369 370 /** 371 * Returns a comparator that compares two {@code char} arrays <a 372 * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>; not advisable 373 * for sorting user-visible strings as the ordering may not match the conventions of the user's 374 * locale. That is, it compares, using {@link #compare(char, char)}), the first pair of values 375 * that follow any common prefix, or when one array is a prefix of the other, treats the shorter 376 * array as the lesser. For example, {@code [] < ['a'] < ['a', 'b'] < ['b']}. 377 * 378 * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays 379 * support only identity equality), but it is consistent with {@link Arrays#equals(char[], 380 * char[])}. 381 * 382 * @since 2.0 383 */ 384 public static Comparator<char[]> lexicographicalComparator() { 385 return LexicographicalComparator.INSTANCE; 386 } 387 388 private enum LexicographicalComparator implements Comparator<char[]> { 389 INSTANCE; 390 391 @Override 392 public int compare(char[] left, char[] right) { 393 int minLength = Math.min(left.length, right.length); 394 for (int i = 0; i < minLength; i++) { 395 int result = Chars.compare(left[i], right[i]); 396 if (result != 0) { 397 return result; 398 } 399 } 400 return left.length - right.length; 401 } 402 403 @Override 404 public String toString() { 405 return "Chars.lexicographicalComparator()"; 406 } 407 } 408 409 /** 410 * Copies a collection of {@code Character} instances into a new array of primitive {@code char} 411 * values. 412 * 413 * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}. 414 * Calling this method is as thread-safe as calling that method. 415 * 416 * @param collection a collection of {@code Character} objects 417 * @return an array containing the same values as {@code collection}, in the same order, converted 418 * to primitives 419 * @throws NullPointerException if {@code collection} or any of its elements is null 420 */ 421 public static char[] toArray(Collection<Character> collection) { 422 if (collection instanceof CharArrayAsList) { 423 return ((CharArrayAsList) collection).toCharArray(); 424 } 425 426 Object[] boxedArray = collection.toArray(); 427 int len = boxedArray.length; 428 char[] array = new char[len]; 429 for (int i = 0; i < len; i++) { 430 // checkNotNull for GWT (do not optimize) 431 array[i] = (Character) checkNotNull(boxedArray[i]); 432 } 433 return array; 434 } 435 436 /** 437 * Sorts the elements of {@code array} in descending order. 438 * 439 * @since 23.1 440 */ 441 public static void sortDescending(char[] array) { 442 checkNotNull(array); 443 sortDescending(array, 0, array.length); 444 } 445 446 /** 447 * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} 448 * exclusive in descending order. 449 * 450 * @since 23.1 451 */ 452 public static void sortDescending(char[] array, int fromIndex, int toIndex) { 453 checkNotNull(array); 454 checkPositionIndexes(fromIndex, toIndex, array.length); 455 Arrays.sort(array, fromIndex, toIndex); 456 reverse(array, fromIndex, toIndex); 457 } 458 459 /** 460 * Reverses the elements of {@code array}. This is equivalent to {@code 461 * Collections.reverse(Chars.asList(array))}, but is likely to be more efficient. 462 * 463 * @since 23.1 464 */ 465 public static void reverse(char[] array) { 466 checkNotNull(array); 467 reverse(array, 0, array.length); 468 } 469 470 /** 471 * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} 472 * exclusive. This is equivalent to {@code 473 * Collections.reverse(Chars.asList(array).subList(fromIndex, toIndex))}, but is likely to be more 474 * efficient. 475 * 476 * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or 477 * {@code toIndex > fromIndex} 478 * @since 23.1 479 */ 480 public static void reverse(char[] array, int fromIndex, int toIndex) { 481 checkNotNull(array); 482 checkPositionIndexes(fromIndex, toIndex, array.length); 483 for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) { 484 char tmp = array[i]; 485 array[i] = array[j]; 486 array[j] = tmp; 487 } 488 } 489 490 /** 491 * Returns a fixed-size list backed by the specified array, similar to {@link 492 * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to 493 * set a value to {@code null} will result in a {@link NullPointerException}. 494 * 495 * <p>The returned list maintains the values, but not the identities, of {@code Character} objects 496 * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for 497 * the returned list is unspecified. 498 * 499 * @param backingArray the array to back the list 500 * @return a list view of the array 501 */ 502 public static List<Character> asList(char... backingArray) { 503 if (backingArray.length == 0) { 504 return Collections.emptyList(); 505 } 506 return new CharArrayAsList(backingArray); 507 } 508 509 @GwtCompatible 510 private static class CharArrayAsList extends AbstractList<Character> 511 implements RandomAccess, Serializable { 512 final char[] array; 513 final int start; 514 final int end; 515 516 CharArrayAsList(char[] array) { 517 this(array, 0, array.length); 518 } 519 520 CharArrayAsList(char[] array, int start, int end) { 521 this.array = array; 522 this.start = start; 523 this.end = end; 524 } 525 526 @Override 527 public int size() { 528 return end - start; 529 } 530 531 @Override 532 public boolean isEmpty() { 533 return false; 534 } 535 536 @Override 537 public Character get(int index) { 538 checkElementIndex(index, size()); 539 return array[start + index]; 540 } 541 542 @Override 543 public boolean contains(Object target) { 544 // Overridden to prevent a ton of boxing 545 return (target instanceof Character) 546 && Chars.indexOf(array, (Character) target, start, end) != -1; 547 } 548 549 @Override 550 public int indexOf(Object target) { 551 // Overridden to prevent a ton of boxing 552 if (target instanceof Character) { 553 int i = Chars.indexOf(array, (Character) target, start, end); 554 if (i >= 0) { 555 return i - start; 556 } 557 } 558 return -1; 559 } 560 561 @Override 562 public int lastIndexOf(Object target) { 563 // Overridden to prevent a ton of boxing 564 if (target instanceof Character) { 565 int i = Chars.lastIndexOf(array, (Character) target, start, end); 566 if (i >= 0) { 567 return i - start; 568 } 569 } 570 return -1; 571 } 572 573 @Override 574 public Character set(int index, Character element) { 575 checkElementIndex(index, size()); 576 char oldValue = array[start + index]; 577 // checkNotNull for GWT (do not optimize) 578 array[start + index] = checkNotNull(element); 579 return oldValue; 580 } 581 582 @Override 583 public List<Character> subList(int fromIndex, int toIndex) { 584 int size = size(); 585 checkPositionIndexes(fromIndex, toIndex, size); 586 if (fromIndex == toIndex) { 587 return Collections.emptyList(); 588 } 589 return new CharArrayAsList(array, start + fromIndex, start + toIndex); 590 } 591 592 @Override 593 public boolean equals(@Nullable Object object) { 594 if (object == this) { 595 return true; 596 } 597 if (object instanceof CharArrayAsList) { 598 CharArrayAsList that = (CharArrayAsList) object; 599 int size = size(); 600 if (that.size() != size) { 601 return false; 602 } 603 for (int i = 0; i < size; i++) { 604 if (array[start + i] != that.array[that.start + i]) { 605 return false; 606 } 607 } 608 return true; 609 } 610 return super.equals(object); 611 } 612 613 @Override 614 public int hashCode() { 615 int result = 1; 616 for (int i = start; i < end; i++) { 617 result = 31 * result + Chars.hashCode(array[i]); 618 } 619 return result; 620 } 621 622 @Override 623 public String toString() { 624 StringBuilder builder = new StringBuilder(size() * 3); 625 builder.append('[').append(array[start]); 626 for (int i = start + 1; i < end; i++) { 627 builder.append(", ").append(array[i]); 628 } 629 return builder.append(']').toString(); 630 } 631 632 char[] toCharArray() { 633 return Arrays.copyOfRange(array, start, end); 634 } 635 636 private static final long serialVersionUID = 0; 637 } 638}