001/*
002 * Copyright (C) 2008 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.escape;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018
019import com.google.common.annotations.Beta;
020import com.google.common.annotations.GwtCompatible;
021
022/**
023 * An {@link Escaper} that converts literal text into a format safe for inclusion in a particular
024 * context (such as an XML document). Typically (but not always), the inverse process of
025 * "unescaping" the text is performed automatically by the relevant parser.
026 *
027 * <p>For example, an XML escaper would convert the literal string {@code "Foo<Bar>"} into {@code
028 * "Foo&lt;Bar&gt;"} to prevent {@code "<Bar>"} from being confused with an XML tag. When the
029 * resulting XML document is parsed, the parser API will return this text as the original literal
030 * string {@code "Foo<Bar>"}.
031 *
032 * <p><b>Note:</b> This class is similar to {@link CharEscaper} but with one very important
033 * difference. A CharEscaper can only process Java <a
034 * href="http://en.wikipedia.org/wiki/UTF-16">UTF16</a> characters in isolation and may not cope
035 * when it encounters surrogate pairs. This class facilitates the correct escaping of all Unicode
036 * characters.
037 *
038 * <p>As there are important reasons, including potential security issues, to handle Unicode
039 * correctly if you are considering implementing a new escaper you should favor using UnicodeEscaper
040 * wherever possible.
041 *
042 * <p>A {@code UnicodeEscaper} instance is required to be stateless, and safe when used concurrently
043 * by multiple threads.
044 *
045 * <p>Popular escapers are defined as constants in classes like {@link
046 * com.google.common.html.HtmlEscapers} and {@link com.google.common.xml.XmlEscapers}. To create
047 * your own escapers extend this class and implement the {@link #escape(int)} method.
048 *
049 * @author David Beaumont
050 * @since 15.0
051 */
052@Beta
053@GwtCompatible
054public abstract class UnicodeEscaper extends Escaper {
055  /** The amount of padding (chars) to use when growing the escape buffer. */
056  private static final int DEST_PAD = 32;
057
058  /** Constructor for use by subclasses. */
059  protected UnicodeEscaper() {}
060
061  /**
062   * Returns the escaped form of the given Unicode code point, or {@code null} if this code point
063   * does not need to be escaped. When called as part of an escaping operation, the given code point
064   * is guaranteed to be in the range {@code 0 <= cp <= Character#MAX_CODE_POINT}.
065   *
066   * <p>If an empty array is returned, this effectively strips the input character from the
067   * resulting text.
068   *
069   * <p>If the character does not need to be escaped, this method should return {@code null}, rather
070   * than an array containing the character representation of the code point. This enables the
071   * escaping algorithm to perform more efficiently.
072   *
073   * <p>If the implementation of this method cannot correctly handle a particular code point then it
074   * should either throw an appropriate runtime exception or return a suitable replacement
075   * character. It must never silently discard invalid input as this may constitute a security risk.
076   *
077   * @param cp the Unicode code point to escape if necessary
078   * @return the replacement characters, or {@code null} if no escaping was needed
079   */
080  protected abstract char[] escape(int cp);
081
082  /**
083   * Scans a sub-sequence of characters from a given {@link CharSequence}, returning the index of
084   * the next character that requires escaping.
085   *
086   * <p><b>Note:</b> When implementing an escaper, it is a good idea to override this method for
087   * efficiency. The base class implementation determines successive Unicode code points and invokes
088   * {@link #escape(int)} for each of them. If the semantics of your escaper are such that code
089   * points in the supplementary range are either all escaped or all unescaped, this method can be
090   * implemented more efficiently using {@link CharSequence#charAt(int)}.
091   *
092   * <p>Note however that if your escaper does not escape characters in the supplementary range, you
093   * should either continue to validate the correctness of any surrogate characters encountered or
094   * provide a clear warning to users that your escaper does not validate its input.
095   *
096   * <p>See {@link com.google.common.net.PercentEscaper} for an example.
097   *
098   * @param csq a sequence of characters
099   * @param start the index of the first character to be scanned
100   * @param end the index immediately after the last character to be scanned
101   * @throws IllegalArgumentException if the scanned sub-sequence of {@code csq} contains invalid
102   *     surrogate pairs
103   */
104  protected int nextEscapeIndex(CharSequence csq, int start, int end) {
105    int index = start;
106    while (index < end) {
107      int cp = codePointAt(csq, index, end);
108      if (cp < 0 || escape(cp) != null) {
109        break;
110      }
111      index += Character.isSupplementaryCodePoint(cp) ? 2 : 1;
112    }
113    return index;
114  }
115
116  /**
117   * Returns the escaped form of a given literal string.
118   *
119   * <p>If you are escaping input in arbitrary successive chunks, then it is not generally safe to
120   * use this method. If an input string ends with an unmatched high surrogate character, then this
121   * method will throw {@link IllegalArgumentException}. You should ensure your input is valid <a
122   * href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> before calling this method.
123   *
124   * <p><b>Note:</b> When implementing an escaper it is a good idea to override this method for
125   * efficiency by inlining the implementation of {@link #nextEscapeIndex(CharSequence, int, int)}
126   * directly. Doing this for {@link com.google.common.net.PercentEscaper} more than doubled the
127   * performance for unescaped strings (as measured by {@link CharEscapersBenchmark}).
128   *
129   * @param string the literal string to be escaped
130   * @return the escaped form of {@code string}
131   * @throws NullPointerException if {@code string} is null
132   * @throws IllegalArgumentException if invalid surrogate characters are encountered
133   */
134  @Override
135  public String escape(String string) {
136    checkNotNull(string);
137    int end = string.length();
138    int index = nextEscapeIndex(string, 0, end);
139    return index == end ? string : escapeSlow(string, index);
140  }
141
142  /**
143   * Returns the escaped form of a given literal string, starting at the given index. This method is
144   * called by the {@link #escape(String)} method when it discovers that escaping is required. It is
145   * protected to allow subclasses to override the fastpath escaping function to inline their
146   * escaping test. See {@link CharEscaperBuilder} for an example usage.
147   *
148   * <p>This method is not reentrant and may only be invoked by the top level {@link
149   * #escape(String)} method.
150   *
151   * @param s the literal string to be escaped
152   * @param index the index to start escaping from
153   * @return the escaped form of {@code string}
154   * @throws NullPointerException if {@code string} is null
155   * @throws IllegalArgumentException if invalid surrogate characters are encountered
156   */
157  protected final String escapeSlow(String s, int index) {
158    int end = s.length();
159
160    // Get a destination buffer and setup some loop variables.
161    char[] dest = Platform.charBufferFromThreadLocal();
162    int destIndex = 0;
163    int unescapedChunkStart = 0;
164
165    while (index < end) {
166      int cp = codePointAt(s, index, end);
167      if (cp < 0) {
168        throw new IllegalArgumentException("Trailing high surrogate at end of input");
169      }
170      // It is possible for this to return null because nextEscapeIndex() may
171      // (for performance reasons) yield some false positives but it must never
172      // give false negatives.
173      char[] escaped = escape(cp);
174      int nextIndex = index + (Character.isSupplementaryCodePoint(cp) ? 2 : 1);
175      if (escaped != null) {
176        int charsSkipped = index - unescapedChunkStart;
177
178        // This is the size needed to add the replacement, not the full
179        // size needed by the string. We only regrow when we absolutely must.
180        int sizeNeeded = destIndex + charsSkipped + escaped.length;
181        if (dest.length < sizeNeeded) {
182          int destLength = sizeNeeded + (end - index) + DEST_PAD;
183          dest = growBuffer(dest, destIndex, destLength);
184        }
185        // If we have skipped any characters, we need to copy them now.
186        if (charsSkipped > 0) {
187          s.getChars(unescapedChunkStart, index, dest, destIndex);
188          destIndex += charsSkipped;
189        }
190        if (escaped.length > 0) {
191          System.arraycopy(escaped, 0, dest, destIndex, escaped.length);
192          destIndex += escaped.length;
193        }
194        // If we dealt with an escaped character, reset the unescaped range.
195        unescapedChunkStart = nextIndex;
196      }
197      index = nextEscapeIndex(s, nextIndex, end);
198    }
199
200    // Process trailing unescaped characters - no need to account for escaped
201    // length or padding the allocation.
202    int charsSkipped = end - unescapedChunkStart;
203    if (charsSkipped > 0) {
204      int endIndex = destIndex + charsSkipped;
205      if (dest.length < endIndex) {
206        dest = growBuffer(dest, destIndex, endIndex);
207      }
208      s.getChars(unescapedChunkStart, end, dest, destIndex);
209      destIndex = endIndex;
210    }
211    return new String(dest, 0, destIndex);
212  }
213
214  /**
215   * Returns the Unicode code point of the character at the given index.
216   *
217   * <p>Unlike {@link Character#codePointAt(CharSequence, int)} or {@link String#codePointAt(int)}
218   * this method will never fail silently when encountering an invalid surrogate pair.
219   *
220   * <p>The behaviour of this method is as follows:
221   *
222   * <ol>
223   *   <li>If {@code index >= end}, {@link IndexOutOfBoundsException} is thrown.
224   *   <li><b>If the character at the specified index is not a surrogate, it is returned.</b>
225   *   <li>If the first character was a high surrogate value, then an attempt is made to read the
226   *       next character.
227   *       <ol>
228   *         <li><b>If the end of the sequence was reached, the negated value of the trailing high
229   *             surrogate is returned.</b>
230   *         <li><b>If the next character was a valid low surrogate, the code point value of the
231   *             high/low surrogate pair is returned.</b>
232   *         <li>If the next character was not a low surrogate value, then {@link
233   *             IllegalArgumentException} is thrown.
234   *       </ol>
235   *   <li>If the first character was a low surrogate value, {@link IllegalArgumentException} is
236   *       thrown.
237   * </ol>
238   *
239   * @param seq the sequence of characters from which to decode the code point
240   * @param index the index of the first character to decode
241   * @param end the index beyond the last valid character to decode
242   * @return the Unicode code point for the given index or the negated value of the trailing high
243   *     surrogate character at the end of the sequence
244   */
245  protected static int codePointAt(CharSequence seq, int index, int end) {
246    checkNotNull(seq);
247    if (index < end) {
248      char c1 = seq.charAt(index++);
249      if (c1 < Character.MIN_HIGH_SURROGATE || c1 > Character.MAX_LOW_SURROGATE) {
250        // Fast path (first test is probably all we need to do)
251        return c1;
252      } else if (c1 <= Character.MAX_HIGH_SURROGATE) {
253        // If the high surrogate was the last character, return its inverse
254        if (index == end) {
255          return -c1;
256        }
257        // Otherwise look for the low surrogate following it
258        char c2 = seq.charAt(index);
259        if (Character.isLowSurrogate(c2)) {
260          return Character.toCodePoint(c1, c2);
261        }
262        throw new IllegalArgumentException(
263            "Expected low surrogate but got char '"
264                + c2
265                + "' with value "
266                + (int) c2
267                + " at index "
268                + index
269                + " in '"
270                + seq
271                + "'");
272      } else {
273        throw new IllegalArgumentException(
274            "Unexpected low surrogate character '"
275                + c1
276                + "' with value "
277                + (int) c1
278                + " at index "
279                + (index - 1)
280                + " in '"
281                + seq
282                + "'");
283      }
284    }
285    throw new IndexOutOfBoundsException("Index exceeds specified range");
286  }
287
288  /**
289   * Helper method to grow the character buffer as needed, this only happens once in a while so it's
290   * ok if it's in a method call. If the index passed in is 0 then no copying will be done.
291   */
292  private static char[] growBuffer(char[] dest, int index, int size) {
293    if (size < 0) { // overflow - should be OutOfMemoryError but GWT/j2cl don't support it
294      throw new AssertionError("Cannot increase internal buffer any further");
295    }
296    char[] copy = new char[size];
297    if (index > 0) {
298      System.arraycopy(dest, 0, copy, 0, index);
299    }
300    return copy;
301  }
302}