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