001/* 002 * Copyright (C) 2010 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.base; 016 017import static com.google.common.base.Preconditions.checkArgument; 018import static com.google.common.base.Preconditions.checkNotNull; 019 020import com.google.common.annotations.GwtCompatible; 021 022/** 023 * Static methods pertaining to ASCII characters (those in the range of values {@code 0x00} through 024 * {@code 0x7F}), and to strings containing such characters. 025 * 026 * <p>ASCII utilities also exist in other classes of this package: 027 * <ul> 028 * <!-- TODO(kevinb): how can we make this not produce a warning when building gwt javadoc? --> 029 * <li>{@link Charsets#US_ASCII} specifies the {@code Charset} of ASCII characters. 030 * <li>{@link CharMatcher#ascii} matches ASCII characters and provides text processing methods which 031 * operate only on the ASCII characters of a string. 032 * </ul> 033 * 034 * @author Craig Berry 035 * @author Gregory Kick 036 * @since 7.0 037 */ 038@GwtCompatible 039public final class Ascii { 040 041 private Ascii() {} 042 043 /* The ASCII control characters, per RFC 20. */ 044 /** 045 * Null ('\0'): The all-zeros character which may serve to accomplish time fill and media fill. 046 * Normally used as a C string terminator. 047 * 048 * <p>Although RFC 20 names this as "Null", note that it is distinct from the C/C++ "NULL" 049 * pointer. 050 * 051 * @since 8.0 052 */ 053 public static final byte NUL = 0; 054 055 /** 056 * Start of Heading: A communication control character used at the beginning of a sequence of 057 * characters which constitute a machine-sensible address or routing information. Such a sequence 058 * is referred to as the "heading." An STX character has the effect of terminating a heading. 059 * 060 * @since 8.0 061 */ 062 public static final byte SOH = 1; 063 064 /** 065 * Start of Text: A communication control character which precedes a sequence of characters that 066 * is to be treated as an entity and entirely transmitted through to the ultimate destination. 067 * Such a sequence is referred to as "text." STX may be used to terminate a sequence of characters 068 * started by SOH. 069 * 070 * @since 8.0 071 */ 072 public static final byte STX = 2; 073 074 /** 075 * End of Text: A communication control character used to terminate a sequence of characters 076 * started with STX and transmitted as an entity. 077 * 078 * @since 8.0 079 */ 080 public static final byte ETX = 3; 081 082 /** 083 * End of Transmission: A communication control character used to indicate the conclusion of a 084 * transmission, which may have contained one or more texts and any associated headings. 085 * 086 * @since 8.0 087 */ 088 public static final byte EOT = 4; 089 090 /** 091 * Enquiry: A communication control character used in data communication systems as a request for 092 * a response from a remote station. It may be used as a "Who Are You" (WRU) to obtain 093 * identification, or may be used to obtain station status, or both. 094 * 095 * @since 8.0 096 */ 097 public static final byte ENQ = 5; 098 099 /** 100 * Acknowledge: A communication control character transmitted by a receiver as an affirmative 101 * response to a sender. 102 * 103 * @since 8.0 104 */ 105 public static final byte ACK = 6; 106 107 /** 108 * Bell ('\a'): A character for use when there is a need to call for human attention. It may 109 * control alarm or attention devices. 110 * 111 * @since 8.0 112 */ 113 public static final byte BEL = 7; 114 115 /** 116 * Backspace ('\b'): A format effector which controls the movement of the printing position one 117 * printing space backward on the same printing line. (Applicable also to display devices.) 118 * 119 * @since 8.0 120 */ 121 public static final byte BS = 8; 122 123 /** 124 * Horizontal Tabulation ('\t'): A format effector which controls the movement of the printing 125 * position to the next in a series of predetermined positions along the printing line. 126 * (Applicable also to display devices and the skip function on punched cards.) 127 * 128 * @since 8.0 129 */ 130 public static final byte HT = 9; 131 132 /** 133 * Line Feed ('\n'): A format effector which controls the movement of the printing position to the 134 * next printing line. (Applicable also to display devices.) Where appropriate, this character may 135 * have the meaning "New Line" (NL), a format effector which controls the movement of the printing 136 * point to the first printing position on the next printing line. Use of this convention requires 137 * agreement between sender and recipient of data. 138 * 139 * @since 8.0 140 */ 141 public static final byte LF = 10; 142 143 /** 144 * Alternate name for {@link #LF}. ({@code LF} is preferred.) 145 * 146 * @since 8.0 147 */ 148 public static final byte NL = 10; 149 150 /** 151 * Vertical Tabulation ('\v'): A format effector which controls the movement of the printing 152 * position to the next in a series of predetermined printing lines. (Applicable also to display 153 * devices.) 154 * 155 * @since 8.0 156 */ 157 public static final byte VT = 11; 158 159 /** 160 * Form Feed ('\f'): A format effector which controls the movement of the printing position to the 161 * first pre-determined printing line on the next form or page. (Applicable also to display 162 * devices.) 163 * 164 * @since 8.0 165 */ 166 public static final byte FF = 12; 167 168 /** 169 * Carriage Return ('\r'): A format effector which controls the movement of the printing position 170 * to the first printing position on the same printing line. (Applicable also to display devices.) 171 * 172 * @since 8.0 173 */ 174 public static final byte CR = 13; 175 176 /** 177 * Shift Out: A control character indicating that the code combinations which follow shall be 178 * interpreted as outside of the character set of the standard code table until a Shift In 179 * character is reached. 180 * 181 * @since 8.0 182 */ 183 public static final byte SO = 14; 184 185 /** 186 * Shift In: A control character indicating that the code combinations which follow shall be 187 * interpreted according to the standard code table. 188 * 189 * @since 8.0 190 */ 191 public static final byte SI = 15; 192 193 /** 194 * Data Link Escape: A communication control character which will change the meaning of a limited 195 * number of contiguously following characters. It is used exclusively to provide supplementary 196 * controls in data communication networks. 197 * 198 * @since 8.0 199 */ 200 public static final byte DLE = 16; 201 202 /** 203 * Device Control 1. Characters for the control of ancillary devices associated with data 204 * processing or telecommunication systems, more especially switching devices "on" or "off." (If a 205 * single "stop" control is required to interrupt or turn off ancillary devices, DC4 is the 206 * preferred assignment.) 207 * 208 * @since 8.0 209 */ 210 public static final byte DC1 = 17; // aka XON 211 212 /** 213 * Transmission On: Although originally defined as DC1, this ASCII control character is now better 214 * known as the XON code used for software flow control in serial communications. The main use is 215 * restarting the transmission after the communication has been stopped by the XOFF control code. 216 * 217 * @since 8.0 218 */ 219 public static final byte XON = 17; // aka DC1 220 221 /** 222 * Device Control 2. Characters for the control of ancillary devices associated with data 223 * processing or telecommunication systems, more especially switching devices "on" or "off." (If a 224 * single "stop" control is required to interrupt or turn off ancillary devices, DC4 is the 225 * preferred assignment.) 226 * 227 * @since 8.0 228 */ 229 public static final byte DC2 = 18; 230 231 /** 232 * Device Control 3. Characters for the control of ancillary devices associated with data 233 * processing or telecommunication systems, more especially switching devices "on" or "off." (If a 234 * single "stop" control is required to interrupt or turn off ancillary devices, DC4 is the 235 * preferred assignment.) 236 * 237 * @since 8.0 238 */ 239 public static final byte DC3 = 19; // aka XOFF 240 241 /** 242 * Transmission off. See {@link #XON} for explanation. 243 * 244 * @since 8.0 245 */ 246 public static final byte XOFF = 19; // aka DC3 247 248 /** 249 * Device Control 4. Characters for the control of ancillary devices associated with data 250 * processing or telecommunication systems, more especially switching devices "on" or "off." (If a 251 * single "stop" control is required to interrupt or turn off ancillary devices, DC4 is the 252 * preferred assignment.) 253 * 254 * @since 8.0 255 */ 256 public static final byte DC4 = 20; 257 258 /** 259 * Negative Acknowledge: A communication control character transmitted by a receiver as a negative 260 * response to the sender. 261 * 262 * @since 8.0 263 */ 264 public static final byte NAK = 21; 265 266 /** 267 * Synchronous Idle: A communication control character used by a synchronous transmission system 268 * in the absence of any other character to provide a signal from which synchronism may be 269 * achieved or retained. 270 * 271 * @since 8.0 272 */ 273 public static final byte SYN = 22; 274 275 /** 276 * End of Transmission Block: A communication control character used to indicate the end of a 277 * block of data for communication purposes. ETB is used for blocking data where the block 278 * structure is not necessarily related to the processing format. 279 * 280 * @since 8.0 281 */ 282 public static final byte ETB = 23; 283 284 /** 285 * Cancel: A control character used to indicate that the data with which it is sent is in error or 286 * is to be disregarded. 287 * 288 * @since 8.0 289 */ 290 public static final byte CAN = 24; 291 292 /** 293 * End of Medium: A control character associated with the sent data which may be used to identify 294 * the physical end of the medium, or the end of the used, or wanted, portion of information 295 * recorded on a medium. (The position of this character does not necessarily correspond to the 296 * physical end of the medium.) 297 * 298 * @since 8.0 299 */ 300 public static final byte EM = 25; 301 302 /** 303 * Substitute: A character that may be substituted for a character which is determined to be 304 * invalid or in error. 305 * 306 * @since 8.0 307 */ 308 public static final byte SUB = 26; 309 310 /** 311 * Escape: A control character intended to provide code extension (supplementary characters) in 312 * general information interchange. The Escape character itself is a prefix affecting the 313 * interpretation of a limited number of contiguously following characters. 314 * 315 * @since 8.0 316 */ 317 public static final byte ESC = 27; 318 319 /** 320 * File Separator: These four information separators may be used within data in optional fashion, 321 * except that their hierarchical relationship shall be: FS is the most inclusive, then GS, then 322 * RS, and US is least inclusive. (The content and length of a File, Group, Record, or Unit are 323 * not specified.) 324 * 325 * @since 8.0 326 */ 327 public static final byte FS = 28; 328 329 /** 330 * Group Separator: These four information separators may be used within data in optional fashion, 331 * except that their hierarchical relationship shall be: FS is the most inclusive, then GS, then 332 * RS, and US is least inclusive. (The content and length of a File, Group, Record, or Unit are 333 * not specified.) 334 * 335 * @since 8.0 336 */ 337 public static final byte GS = 29; 338 339 /** 340 * Record Separator: These four information separators may be used within data in optional 341 * fashion, except that their hierarchical relationship shall be: FS is the most inclusive, then 342 * GS, then RS, and US is least inclusive. (The content and length of a File, Group, Record, or 343 * Unit are not specified.) 344 * 345 * @since 8.0 346 */ 347 public static final byte RS = 30; 348 349 /** 350 * Unit Separator: These four information separators may be used within data in optional fashion, 351 * except that their hierarchical relationship shall be: FS is the most inclusive, then GS, then 352 * RS, and US is least inclusive. (The content and length of a File, Group, Record, or Unit are 353 * not specified.) 354 * 355 * @since 8.0 356 */ 357 public static final byte US = 31; 358 359 /** 360 * Space: A normally non-printing graphic character used to separate words. It is also a format 361 * effector which controls the movement of the printing position, one printing position forward. 362 * (Applicable also to display devices.) 363 * 364 * @since 8.0 365 */ 366 public static final byte SP = 32; 367 368 /** 369 * Alternate name for {@link #SP}. 370 * 371 * @since 8.0 372 */ 373 public static final byte SPACE = 32; 374 375 /** 376 * Delete: This character is used primarily to "erase" or "obliterate" erroneous or unwanted 377 * characters in perforated tape. 378 * 379 * @since 8.0 380 */ 381 public static final byte DEL = 127; 382 383 /** 384 * The minimum value of an ASCII character. 385 * 386 * @since 9.0 (was type {@code int} before 12.0) 387 */ 388 public static final char MIN = 0; 389 390 /** 391 * The maximum value of an ASCII character. 392 * 393 * @since 9.0 (was type {@code int} before 12.0) 394 */ 395 public static final char MAX = 127; 396 397 /** 398 * Returns a copy of the input string in which all {@linkplain #isUpperCase(char) uppercase ASCII 399 * characters} have been converted to lowercase. All other characters are copied without 400 * modification. 401 */ 402 public static String toLowerCase(String string) { 403 int length = string.length(); 404 for (int i = 0; i < length; i++) { 405 if (isUpperCase(string.charAt(i))) { 406 char[] chars = string.toCharArray(); 407 for (; i < length; i++) { 408 char c = chars[i]; 409 if (isUpperCase(c)) { 410 chars[i] = (char) (c ^ 0x20); 411 } 412 } 413 return String.valueOf(chars); 414 } 415 } 416 return string; 417 } 418 419 /** 420 * Returns a copy of the input character sequence in which all {@linkplain #isUpperCase(char) 421 * uppercase ASCII characters} have been converted to lowercase. All other characters are copied 422 * without modification. 423 * 424 * @since 14.0 425 */ 426 public static String toLowerCase(CharSequence chars) { 427 if (chars instanceof String) { 428 return toLowerCase((String) chars); 429 } 430 char[] newChars = new char[chars.length()]; 431 for (int i = 0; i < newChars.length; i++) { 432 newChars[i] = toLowerCase(chars.charAt(i)); 433 } 434 return String.valueOf(newChars); 435 } 436 437 /** 438 * If the argument is an {@linkplain #isUpperCase(char) uppercase ASCII character} returns the 439 * lowercase equivalent. Otherwise returns the argument. 440 */ 441 public static char toLowerCase(char c) { 442 return isUpperCase(c) ? (char) (c ^ 0x20) : c; 443 } 444 445 /** 446 * Returns a copy of the input string in which all {@linkplain #isLowerCase(char) lowercase ASCII 447 * characters} have been converted to uppercase. All other characters are copied without 448 * modification. 449 */ 450 public static String toUpperCase(String string) { 451 int length = string.length(); 452 for (int i = 0; i < length; i++) { 453 if (isLowerCase(string.charAt(i))) { 454 char[] chars = string.toCharArray(); 455 for (; i < length; i++) { 456 char c = chars[i]; 457 if (isLowerCase(c)) { 458 chars[i] = (char) (c & 0x5f); 459 } 460 } 461 return String.valueOf(chars); 462 } 463 } 464 return string; 465 } 466 467 /** 468 * Returns a copy of the input character sequence in which all {@linkplain #isLowerCase(char) 469 * lowercase ASCII characters} have been converted to uppercase. All other characters are copied 470 * without modification. 471 * 472 * @since 14.0 473 */ 474 public static String toUpperCase(CharSequence chars) { 475 if (chars instanceof String) { 476 return toUpperCase((String) chars); 477 } 478 char[] newChars = new char[chars.length()]; 479 for (int i = 0; i < newChars.length; i++) { 480 newChars[i] = toUpperCase(chars.charAt(i)); 481 } 482 return String.valueOf(newChars); 483 } 484 485 /** 486 * If the argument is a {@linkplain #isLowerCase(char) lowercase ASCII character} returns the 487 * uppercase equivalent. Otherwise returns the argument. 488 */ 489 public static char toUpperCase(char c) { 490 return isLowerCase(c) ? (char) (c & 0x5f) : c; 491 } 492 493 /** 494 * Indicates whether {@code c} is one of the twenty-six lowercase ASCII alphabetic characters 495 * between {@code 'a'} and {@code 'z'} inclusive. All others (including non-ASCII characters) 496 * return {@code false}. 497 */ 498 public static boolean isLowerCase(char c) { 499 // Note: This was benchmarked against the alternate expression "(char)(c - 'a') < 26" (Nov '13) 500 // and found to perform at least as well, or better. 501 return (c >= 'a') && (c <= 'z'); 502 } 503 504 /** 505 * Indicates whether {@code c} is one of the twenty-six uppercase ASCII alphabetic characters 506 * between {@code 'A'} and {@code 'Z'} inclusive. All others (including non-ASCII characters) 507 * return {@code false}. 508 */ 509 public static boolean isUpperCase(char c) { 510 return (c >= 'A') && (c <= 'Z'); 511 } 512 513 /** 514 * Truncates the given character sequence to the given maximum length. If the length of the 515 * sequence is greater than {@code maxLength}, the returned string will be exactly 516 * {@code maxLength} chars in length and will end with the given {@code truncationIndicator}. 517 * Otherwise, the sequence will be returned as a string with no changes to the content. 518 * 519 * <p>Examples: 520 * 521 * <pre> {@code 522 * Ascii.truncate("foobar", 7, "..."); // returns "foobar" 523 * Ascii.truncate("foobar", 5, "..."); // returns "fo..." }</pre> 524 * 525 * <p><b>Note:</b> This method <i>may</i> work with certain non-ASCII text but is not safe for use 526 * with arbitrary Unicode text. It is mostly intended for use with text that is known to be safe 527 * for use with it (such as all-ASCII text) and for simple debugging text. When using this method, 528 * consider the following: 529 * 530 * <ul> 531 * <li>it may split surrogate pairs 532 * <li>it may split characters and combining characters 533 * <li>it does not consider word boundaries 534 * <li>if truncating for display to users, there are other considerations that must be taken into 535 * account 536 * <li>the appropriate truncation indicator may be locale-dependent 537 * <li>it is safe to use non-ASCII characters in the truncation indicator 538 * </ul> 539 * 540 * 541 * @throws IllegalArgumentException if {@code maxLength} is less than the length of 542 * {@code truncationIndicator} 543 * @since 16.0 544 */ 545 public static String truncate(CharSequence seq, int maxLength, String truncationIndicator) { 546 checkNotNull(seq); 547 548 // length to truncate the sequence to, not including the truncation indicator 549 int truncationLength = maxLength - truncationIndicator.length(); 550 551 // in this worst case, this allows a maxLength equal to the length of the truncationIndicator, 552 // meaning that a string will be truncated to just the truncation indicator itself 553 checkArgument( 554 truncationLength >= 0, 555 "maxLength (%s) must be >= length of the truncation indicator (%s)", 556 maxLength, 557 truncationIndicator.length()); 558 559 if (seq.length() <= maxLength) { 560 String string = seq.toString(); 561 if (string.length() <= maxLength) { 562 return string; 563 } 564 // if the length of the toString() result was > maxLength for some reason, truncate that 565 seq = string; 566 } 567 568 return new StringBuilder(maxLength) 569 .append(seq, 0, truncationLength) 570 .append(truncationIndicator) 571 .toString(); 572 } 573 574 /** 575 * Indicates whether the contents of the given character sequences {@code s1} and {@code s2} are 576 * equal, ignoring the case of any ASCII alphabetic characters between {@code 'a'} and {@code 'z'} 577 * or {@code 'A'} and {@code 'Z'} inclusive. 578 * 579 * <p>This method is significantly faster than {@link String#equalsIgnoreCase} and should be used 580 * in preference if at least one of the parameters is known to contain only ASCII characters. 581 * 582 * <p>Note however that this method does not always behave identically to expressions such as: 583 * <ul> 584 * <li>{@code string.toUpperCase().equals("UPPER CASE ASCII")} 585 * <li>{@code string.toLowerCase().equals("lower case ascii")} 586 * </ul> 587 * <p>due to case-folding of some non-ASCII characters (which does not occur in 588 * {@link String#equalsIgnoreCase}). However in almost all cases that ASCII strings are used, the 589 * author probably wanted the behavior provided by this method rather than the subtle and 590 * sometimes surprising behavior of {@code toUpperCase()} and {@code toLowerCase()}. 591 * 592 * @since 16.0 593 */ 594 public static boolean equalsIgnoreCase(CharSequence s1, CharSequence s2) { 595 // Calling length() is the null pointer check (so do it before we can exit early). 596 int length = s1.length(); 597 if (s1 == s2) { 598 return true; 599 } 600 if (length != s2.length()) { 601 return false; 602 } 603 for (int i = 0; i < length; i++) { 604 char c1 = s1.charAt(i); 605 char c2 = s2.charAt(i); 606 if (c1 == c2) { 607 continue; 608 } 609 int alphaIndex = getAlphaIndex(c1); 610 // This was also benchmarked using '&' to avoid branching (but always evaluate the rhs), 611 // however this showed no obvious improvement. 612 if (alphaIndex < 26 && alphaIndex == getAlphaIndex(c2)) { 613 continue; 614 } 615 return false; 616 } 617 return true; 618 } 619 620 /** 621 * Returns the non-negative index value of the alpha character {@code c}, regardless of case. Ie, 622 * 'a'/'A' returns 0 and 'z'/'Z' returns 25. Non-alpha characters return a value of 26 or greater. 623 */ 624 private static int getAlphaIndex(char c) { 625 // Fold upper-case ASCII to lower-case and make zero-indexed and unsigned (by casting to char). 626 return (char) ((c | 0x20) - 'a'); 627 } 628}