001/*
002 * Copyright (C) 2006 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;
018import static java.lang.System.arraycopy;
019
020import com.google.common.annotations.GwtCompatible;
021import org.jspecify.annotations.Nullable;
022
023/**
024 * An object that converts literal text into a format safe for inclusion in a particular context
025 * (such as an XML document). Typically (but not always), the inverse process of "unescaping" the
026 * text is performed automatically by the relevant parser.
027 *
028 * <p>For example, an XML escaper would convert the literal string {@code "Foo<Bar>"} into {@code
029 * "Foo&lt;Bar&gt;"} to prevent {@code "<Bar>"} from being confused with an XML tag. When the
030 * resulting XML document is parsed, the parser API will return this text as the original literal
031 * string {@code "Foo<Bar>"}.
032 *
033 * <p>A {@code CharEscaper} instance is required to be stateless, and safe when used concurrently by
034 * multiple threads.
035 *
036 * <p>Popular escapers are defined as constants in classes like {@link
037 * com.google.common.html.HtmlEscapers} and {@link com.google.common.xml.XmlEscapers}. To create
038 * your own escapers extend this class and implement the {@link #escape(char)} method.
039 *
040 * @author Sven Mawson
041 * @since 15.0
042 */
043@GwtCompatible
044@SuppressWarnings("EscapedEntity") // We do mean for the user to see "&lt;" etc.
045public abstract class CharEscaper extends Escaper {
046  /** Constructor for use by subclasses. */
047  protected CharEscaper() {}
048
049  /**
050   * Returns the escaped form of a given literal string.
051   *
052   * @param string the literal string to be escaped
053   * @return the escaped form of {@code string}
054   * @throws NullPointerException if {@code string} is null
055   */
056  @Override
057  public String escape(String string) {
058    checkNotNull(string); // GWT specific check (do not optimize)
059    // Inlineable fast-path loop which hands off to escapeSlow() only if needed
060    int length = string.length();
061    for (int index = 0; index < length; index++) {
062      if (escape(string.charAt(index)) != null) {
063        return escapeSlow(string, index);
064      }
065    }
066    return string;
067  }
068
069  /**
070   * Returns the escaped form of the given character, or {@code null} if this character does not
071   * need to be escaped. If an empty array is returned, this effectively strips the input character
072   * from the resulting text.
073   *
074   * <p>If the character does not need to be escaped, this method should return {@code null}, rather
075   * than a one-character array containing the character itself. This enables the escaping algorithm
076   * to perform more efficiently.
077   *
078   * <p>An escaper is expected to be able to deal with any {@code char} value, so this method should
079   * not throw any exceptions.
080   *
081   * @param c the character to escape if necessary
082   * @return the replacement characters, or {@code null} if no escaping was needed
083   */
084  protected abstract char @Nullable [] escape(char c);
085
086  final char @Nullable [] escapeInternal(char c) {
087    return escape(c);
088  }
089
090  /**
091   * Returns the escaped form of a given literal string, starting at the given index. This method is
092   * called by the {@link #escape(String)} method when it discovers that escaping is required. It is
093   * protected to allow subclasses to override the fastpath escaping function to inline their
094   * escaping test. See {@link CharEscaperBuilder} for an example usage.
095   *
096   * @param s the literal string to be escaped
097   * @param index the index to start escaping from
098   * @return the escaped form of {@code string}
099   * @throws NullPointerException if {@code string} is null
100   */
101  protected final String escapeSlow(String s, int index) {
102    int slen = s.length();
103
104    // Get a destination buffer and setup some loop variables.
105    char[] dest = Platform.charBufferFromThreadLocal();
106    int destSize = dest.length;
107    int destIndex = 0;
108    int lastEscape = 0;
109
110    // Loop through the rest of the string, replacing when needed into the
111    // destination buffer, which gets grown as needed as well.
112    for (; index < slen; index++) {
113
114      // Get a replacement for the current character.
115      char[] r = escape(s.charAt(index));
116
117      // If no replacement is needed, just continue.
118      if (r == null) {
119        continue;
120      }
121
122      int rlen = r.length;
123      int charsSkipped = index - lastEscape;
124
125      // This is the size needed to add the replacement, not the full size
126      // needed by the string. We only regrow when we absolutely must, and
127      // when we do grow, grow enough to avoid excessive growing. Grow.
128      int sizeNeeded = destIndex + charsSkipped + rlen;
129      if (destSize < sizeNeeded) {
130        destSize = sizeNeeded + DEST_PAD_MULTIPLIER * (slen - index);
131        dest = growBuffer(dest, destIndex, destSize);
132      }
133
134      // If we have skipped any characters, we need to copy them now.
135      if (charsSkipped > 0) {
136        s.getChars(lastEscape, index, dest, destIndex);
137        destIndex += charsSkipped;
138      }
139
140      // Copy the replacement string into the dest buffer as needed.
141      if (rlen > 0) {
142        arraycopy(r, 0, dest, destIndex, rlen);
143        destIndex += rlen;
144      }
145      lastEscape = index + 1;
146    }
147
148    // Copy leftover characters if there are any.
149    int charsLeft = slen - lastEscape;
150    if (charsLeft > 0) {
151      int sizeNeeded = destIndex + charsLeft;
152      if (destSize < sizeNeeded) {
153
154        // Regrow and copy, expensive! No padding as this is the final copy.
155        dest = growBuffer(dest, destIndex, sizeNeeded);
156      }
157      s.getChars(lastEscape, slen, dest, destIndex);
158      destIndex = sizeNeeded;
159    }
160    return new String(dest, 0, destIndex);
161  }
162
163  /**
164   * Helper method to grow the character buffer as needed, this only happens once in a while so it's
165   * ok if it's in a method call. If the index passed in is 0 then no copying will be done.
166   */
167  private static char[] growBuffer(char[] dest, int index, int size) {
168    if (size < 0) { // overflow - should be OutOfMemoryError but GWT/j2cl don't support it
169      throw new AssertionError("Cannot increase internal buffer any further");
170    }
171    char[] copy = new char[size];
172    if (index > 0) {
173      arraycopy(dest, 0, copy, 0, index);
174    }
175    return copy;
176  }
177
178  /** The multiplier for padding to use when growing the escape buffer. */
179  private static final int DEST_PAD_MULTIPLIER = 2;
180}