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 Craig 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  /**
399   * Returns a copy of the input string in which all {@linkplain #isUpperCase(char) uppercase ASCII
400   * characters} have been converted to lowercase. All other characters are copied without
401   * modification.
402   */
403  public static String toLowerCase(String string) {
404    int length = string.length();
405    for (int i = 0; i < length; i++) {
406      if (isUpperCase(string.charAt(i))) {
407        char[] chars = string.toCharArray();
408        for (; i < length; i++) {
409          char c = chars[i];
410          if (isUpperCase(c)) {
411            chars[i] = (char) (c ^ 0x20);
412          }
413        }
414        return String.valueOf(chars);
415      }
416    }
417    return string;
418  }
419
420  /**
421   * Returns a copy of the input character sequence in which all {@linkplain #isUpperCase(char)
422   * uppercase ASCII characters} have been converted to lowercase. All other characters are copied
423   * without modification.
424   *
425   * @since 14.0
426   */
427  public static String toLowerCase(CharSequence chars) {
428    if (chars instanceof String) {
429      return toLowerCase((String) chars);
430    }
431    char[] newChars = new char[chars.length()];
432    for (int i = 0; i < newChars.length; i++) {
433      newChars[i] = toLowerCase(chars.charAt(i));
434    }
435    return String.valueOf(newChars);
436  }
437
438  /**
439   * If the argument is an {@linkplain #isUpperCase(char) uppercase ASCII character} returns the
440   * lowercase equivalent. Otherwise returns the argument.
441   */
442  public static char toLowerCase(char c) {
443    return isUpperCase(c) ? (char) (c ^ 0x20) : c;
444  }
445
446  /**
447   * Returns a copy of the input string in which all {@linkplain #isLowerCase(char) lowercase ASCII
448   * characters} have been converted to uppercase. All other characters are copied without
449   * modification.
450   */
451  public static String toUpperCase(String string) {
452    int length = string.length();
453    for (int i = 0; i < length; i++) {
454      if (isLowerCase(string.charAt(i))) {
455        char[] chars = string.toCharArray();
456        for (; i < length; i++) {
457          char c = chars[i];
458          if (isLowerCase(c)) {
459            chars[i] = (char) (c & 0x5f);
460          }
461        }
462        return String.valueOf(chars);
463      }
464    }
465    return string;
466  }
467
468  /**
469   * Returns a copy of the input character sequence in which all {@linkplain #isLowerCase(char)
470   * lowercase ASCII characters} have been converted to uppercase. All other characters are copied
471   * without modification.
472   *
473   * @since 14.0
474   */
475  public static String toUpperCase(CharSequence chars) {
476    if (chars instanceof String) {
477      return toUpperCase((String) chars);
478    }
479    char[] newChars = new char[chars.length()];
480    for (int i = 0; i < newChars.length; i++) {
481      newChars[i] = toUpperCase(chars.charAt(i));
482    }
483    return String.valueOf(newChars);
484  }
485
486  /**
487   * If the argument is a {@linkplain #isLowerCase(char) lowercase ASCII character} returns the
488   * uppercase equivalent. Otherwise returns the argument.
489   */
490  public static char toUpperCase(char c) {
491    return isLowerCase(c) ? (char) (c & 0x5f) : c;
492  }
493
494  /**
495   * Indicates whether {@code c} is one of the twenty-six lowercase ASCII alphabetic characters
496   * between {@code 'a'} and {@code 'z'} inclusive. All others (including non-ASCII characters)
497   * return {@code false}.
498   */
499  public static boolean isLowerCase(char c) {
500    // Note: This was benchmarked against the alternate expression "(char)(c - 'a') < 26" (Nov '13)
501    // and found to perform at least as well, or better.
502    return (c >= 'a') && (c <= 'z');
503  }
504
505  /**
506   * Indicates whether {@code c} is one of the twenty-six uppercase ASCII alphabetic characters
507   * between {@code 'A'} and {@code 'Z'} inclusive. All others (including non-ASCII characters)
508   * return {@code false}.
509   */
510  public static boolean isUpperCase(char c) {
511    return (c >= 'A') && (c <= 'Z');
512  }
513
514  /**
515   * Truncates the given character sequence to the given maximum length. If the length of the
516   * sequence is greater than {@code maxLength}, the returned string will be exactly {@code
517   * maxLength} chars in length and will end with the given {@code truncationIndicator}. Otherwise,
518   * the sequence will be returned as a string with no changes to the content.
519   *
520   * <p>Examples:
521   *
522   * <pre>{@code
523   * Ascii.truncate("foobar", 7, "..."); // returns "foobar"
524   * Ascii.truncate("foobar", 5, "..."); // returns "fo..."
525   * }</pre>
526   *
527   * <p><b>Note:</b> This method <i>may</i> work with certain non-ASCII text but is not safe for use
528   * with arbitrary Unicode text. It is mostly intended for use with text that is known to be safe
529   * for use with it (such as all-ASCII text) and for simple debugging text. When using this method,
530   * consider the following:
531   *
532   * <ul>
533   *   <li>it may split surrogate pairs
534   *   <li>it may split characters and combining characters
535   *   <li>it does not consider word boundaries
536   *   <li>if truncating for display to users, there are other considerations that must be taken
537   *       into account
538   *   <li>the appropriate truncation indicator may be locale-dependent
539   *   <li>it is safe to use non-ASCII characters in the truncation indicator
540   * </ul>
541   *
542   *
543   * @throws IllegalArgumentException if {@code maxLength} is less than the length of {@code
544   *     truncationIndicator}
545   * @since 16.0
546   */
547  public static String truncate(CharSequence seq, int maxLength, String truncationIndicator) {
548    checkNotNull(seq);
549
550    // length to truncate the sequence to, not including the truncation indicator
551    int truncationLength = maxLength - truncationIndicator.length();
552
553    // in this worst case, this allows a maxLength equal to the length of the truncationIndicator,
554    // meaning that a string will be truncated to just the truncation indicator itself
555    checkArgument(
556        truncationLength >= 0,
557        "maxLength (%s) must be >= length of the truncation indicator (%s)",
558        maxLength,
559        truncationIndicator.length());
560
561    if (seq.length() <= maxLength) {
562      String string = seq.toString();
563      if (string.length() <= maxLength) {
564        return string;
565      }
566      // if the length of the toString() result was > maxLength for some reason, truncate that
567      seq = string;
568    }
569
570    return new StringBuilder(maxLength)
571        .append(seq, 0, truncationLength)
572        .append(truncationIndicator)
573        .toString();
574  }
575
576  /**
577   * Indicates whether the contents of the given character sequences {@code s1} and {@code s2} are
578   * equal, ignoring the case of any ASCII alphabetic characters between {@code 'a'} and {@code 'z'}
579   * or {@code 'A'} and {@code 'Z'} inclusive.
580   *
581   * <p>This method is significantly faster than {@link String#equalsIgnoreCase} and should be used
582   * in preference if at least one of the parameters is known to contain only ASCII characters.
583   *
584   * <p>Note however that this method does not always behave identically to expressions such as:
585   *
586   * <ul>
587   *   <li>{@code string.toUpperCase().equals("UPPER CASE ASCII")}
588   *   <li>{@code string.toLowerCase().equals("lower case ascii")}
589   * </ul>
590   *
591   * <p>due to case-folding of some non-ASCII characters (which does not occur in {@link
592   * String#equalsIgnoreCase}). However in almost all cases that ASCII strings are used, the author
593   * probably wanted the behavior provided by this method rather than the subtle and sometimes
594   * surprising behavior of {@code toUpperCase()} and {@code toLowerCase()}.
595   *
596   * @since 16.0
597   */
598  public static boolean equalsIgnoreCase(CharSequence s1, CharSequence s2) {
599    // Calling length() is the null pointer check (so do it before we can exit early).
600    int length = s1.length();
601    if (s1 == s2) {
602      return true;
603    }
604    if (length != s2.length()) {
605      return false;
606    }
607    for (int i = 0; i < length; i++) {
608      char c1 = s1.charAt(i);
609      char c2 = s2.charAt(i);
610      if (c1 == c2) {
611        continue;
612      }
613      int alphaIndex = getAlphaIndex(c1);
614      // This was also benchmarked using '&' to avoid branching (but always evaluate the rhs),
615      // however this showed no obvious improvement.
616      if (alphaIndex < 26 && alphaIndex == getAlphaIndex(c2)) {
617        continue;
618      }
619      return false;
620    }
621    return true;
622  }
623
624  /**
625   * Returns the non-negative index value of the alpha character {@code c}, regardless of case. Ie,
626   * 'a'/'A' returns 0 and 'z'/'Z' returns 25. Non-alpha characters return a value of 26 or greater.
627   */
628  private static int getAlphaIndex(char c) {
629    // Fold upper-case ASCII to lower-case and make zero-indexed and unsigned (by casting to char).
630    return (char) ((c | 0x20) - 'a');
631  }
632}