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