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