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