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